How to randomly select an item from a list?

后端 未结 15 1326
伪装坚强ぢ
伪装坚强ぢ 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:37

    foo = ['a', 'b', 'c', 'd', 'e']
    number_of_samples = 1
    

    In python 2:

    random_items = random.sample(population=foo, k=number_of_samples)
    

    In python 3:

    random_items = random.choices(population=foo, k=number_of_samples)
    

提交回复
热议问题