我有一个带有列表的Python脚本,我正试图从列表中获取随机项并将它们放入变量中,但我注意到,当我运行程序几次(大约20次)后,它最终会打印出两个相同的项,如“apples”。你知道吗
import random
list = ['apples','grapes','bannas','peaches','pears','oranges','mangos']
a = random.choice(list)
b = random.choice(list)
while a in (list[0],list[1],list[2],list[3],list[4],list[5],list[6]):
a = random.choice(list)
while b in (list[0],list[1],list[2],list[3],list[4],list[5],list[6]):
b = random.choice(list)
print(a + ' ' + b)
while循环应该使变量每次都包含一个唯一的值,但是它没有。你知道吗
上面的Kevins
sample
更好,但我认为这就是你试图用choice
做的:几句话:
list
是python的build in function。千万不要把某件事列在清单上(或口述或删除等)while a in (list[0],list[1],list[2],list[3],list[4],list[5],list[6]):
等价于while a in list:
。因为a
只包含列表中的值,所以条件总是true,循环永远不会结束,也永远不会到达print语句。你知道吗要从一个集合中选择多个唯一的随机项,请使用
sample
而不是choice
。你知道吗另一种选择是:如果你不在乎列表,我会用
pop
,如果你在乎,你可以复制一份,然后用pop
(我不知道你想怎么用你的列表)。你知道吗另一种方法是把你的单子搅乱,然后按顺序一个接一个地拣起来。你知道吗
使用流行音乐,再次:
相关问题 更多 >
编程相关推荐