How to randomly select an item from a list?

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

    Use random.choice()

    import random
    
    foo = ['a', 'b', 'c', 'd', 'e']
    print(random.choice(foo))
    

    For cryptographically secure random choices (e.g. for generating a passphrase from a wordlist) use secrets.choice()

    import secrets
    
    foo = ['battery', 'correct', 'horse', 'staple']
    print(secrets.choice(foo))
    

    secrets is new in Python 3.6, on older versions of Python you can use the random.SystemRandom class:

    import random
    
    secure_random = random.SystemRandom()
    print(secure_random.choice(foo))
    

提交回复
热议问题