How to randomly select an item from a list?

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

    How to randomly select an item from a list?

    Assume I have the following list:

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

    What is the simplest way to retrieve an item at random from this list?

    If you want close to truly random, then I suggest secrets.choice from the standard library (New in Python 3.6.):

    >>> from secrets import choice         # Python 3 only
    >>> choice(list('abcde'))
    'c'
    

    The above is equivalent to my former recommendation, using a SystemRandom object from the random module with the choice method - available earlier in Python 2:

    >>> import random                      # Python 2 compatible
    >>> sr = random.SystemRandom()
    >>> foo = list('abcde')
    >>> foo
    ['a', 'b', 'c', 'd', 'e']
    

    And now:

    >>> sr.choice(foo)
    'd'
    >>> sr.choice(foo)
    'e'
    >>> sr.choice(foo)
    'a'
    >>> sr.choice(foo)
    'b'
    >>> sr.choice(foo)
    'a'
    >>> sr.choice(foo)
    'c'
    >>> sr.choice(foo)
    'c'
    

    If you want a deterministic pseudorandom selection, use the choice function (which is actually a bound method on a Random object):

    >>> random.choice
    >
    

    It seems random, but it's actually not, which we can see if we reseed it repeatedly:

    >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
    ('d', 'a', 'b')
    >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
    ('d', 'a', 'b')
    >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
    ('d', 'a', 'b')
    >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
    ('d', 'a', 'b')
    >>> random.seed(42); random.choice(foo), random.choice(foo), random.choice(foo)
    ('d', 'a', 'b')
    

    A comment:

    This is not about whether random.choice is truly random or not. If you fix the seed, you will get the reproducible results -- and that's what seed is designed for. You can pass a seed to SystemRandom, too. sr = random.SystemRandom(42)

    Well, yes you can pass it a "seed" argument, but you'll see that the SystemRandom object simply ignores it:

    def seed(self, *args, **kwds):
        "Stub method.  Not used for a system random number generator."
        return None
    

提交回复
热议问题