How to randomly select an item from a list?

后端 未结 15 1362
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  梦毁少年i
    2020-11-21 08:13

    As of Python 3.6 you can use the secrets module, which is preferable to the random module for cryptography or security uses.

    To print a random element from a list:

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

    To print a random index:

    print(secrets.randbelow(len(foo)))
    

    For details, see PEP 506.

提交回复
热议问题