gpt4 book ai didi

python - 随机选择一个列表中不在第二个列表中的元素

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:56 30 4
gpt4 key购买 nike

假设我有一个 list2,其中的元素是从大型 list1 中随机选择的。是否有一种聪明的方法可以从 list1 中选择 list2 中不存在的元素?

例如:

list1 = range(20,100)
list2 = [37,49,22,35,72] # could be much longer

while True:
n = random.choice(list1)
if n not in list2:
break

# now n is an element of list1 that's not in list2

我觉得一定有一种比猜测和检查 while 循环更有效的方法。

最佳答案

您可以从 list1 中减去 list2:

list3 = list(set(list1)-set(list2))

然后随机选择:

random.choice(list3)

注意:您需要重新转换 set列表

关于python - 随机选择一个列表中不在第二个列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33343675/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com