How to randomly select an item from a list?

后端 未结 15 1331
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 07:49

Assume I have the following list:

foo = [\'a\', \'b\', \'c\', \'d\', \'e\']

What is the simplest way to retrieve an item at random from thi

15条回答
  •  旧巷少年郎
    2020-11-21 08:13

    If you also need the index, use random.randrange

    from random import randrange
    random_index = randrange(len(foo))
    print(foo[random_index])
    

提交回复
热议问题