北城已荒凉 2008-11-20 18:42 采纳率: 0%
浏览 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条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办