How to randomly select an item from a list?

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

    The following code demonstrates if you need to produce the same items. You can also specify how many samples you want to extract.
    The sample method returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples.

    import random as random
    random.seed(0)  # don't use seed function, if you want different results in each run
    print(random.sample(foo,3))  # 3 is the number of sample you want to retrieve
    
    Output:['d', 'e', 'a']
    

提交回复
热议问题