How to randomly select an item from a list?

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

    numpy solution: numpy.random.choice

    For this question, it works the same as the accepted answer (import random; random.choice()), but I added it because the programmer may have imported numpy already (like me) & also there are some differences between the two methods that may concern your actual use case.

    import numpy as np    
    np.random.choice(foo) # randomly selects a single item
    

    For reproducibility, you can do:

    np.random.seed(123)
    np.random.choice(foo) # first call will always return 'c'
    

    For samples of one or more items, returned as an array, pass the size argument:

    np.random.choice(foo, 5)          # sample with replacement (default)
    np.random.choice(foo, 5, False)   # sample without replacement
    

提交回复
热议问题