除了列表中的给定项目外,从列表中随机选择项目的最简单方法是什么?
示例:list = [2, 4, 5, 7, 9, 34, 54,]
如何随机选择除7以外的任何数字?
有两种主要策略:
从列表中删除异常,并从中取样:
import random
def choice_excluding(lst, exception):
possible_choices = [v for v in lst if v != exception]
return random.choice(possible_choices)
或者从你的完整列表中随机选择一个,只要你得到了禁止值(拒绝采样(,就再试一次:
def reject_sample(lst, exception):
while True:
choice = random.choice(lst)
if choice != exception:
return choice
两者都会得到相同的结果(好吧,只要随机情况相同…(:
lst = [2, 4, 5, 7, 9, 34, 54]
choice_excluding(lst, 7)
# 9
reject_sample(lst, 7)
# 54
根据列表的大小,其中一个可能比另一个更快。试试看!