北城已荒凉 2008-11-20 18:42 采纳率: 100%
浏览 1588
已采纳

如何从列表中随机选择一个项目?

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?

转载于:https://stackoverflow.com/questions/306400/how-to-randomly-select-an-item-from-a-list

  • 写回答

15条回答 默认 最新

  • bug^君 2008-11-20 18:46
    关注

    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 random.SystemRandom class:

    import random
    
    foo = ['battery', 'correct', 'horse', 'staple']
    secure_random = random.SystemRandom()
    print(secure_random.choice(foo))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(14条)

报告相同问题?