使用后如何从列表中删除项目随机选择()?

2024-10-06 16:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有列表的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循环应该使变量每次都包含一个唯一的值,但是它没有。你知道吗


Tags: inimport程序脚本列表randomlistchoice
3条回答

上面的Kevinssample更好,但我认为这就是你试图用choice做的:

import random

fruit = ['apples', 'grapes', 'bannas', 'peaches', 'pears', 'oranges', 'mangos']
a_fruit = random.choice(fruit)
b_fruit = random.choice(fruit)

while a_fruit == b_fruit:
    b_fruit = random.choice(fruit)

print("{} - {}".format(a_fruit, b_fruit))

几句话:

  • list是python的build in function。千万不要把某件事列在清单上(或口述或删除等)
  • 正如kevin提到的那样,while循环是无用的,并且将永远运行,因为它应该始终评估为true。你知道吗

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。你知道吗

>>> list = ['apples','grapes','bannas','peaches','pears','oranges','mangos']
>>> a,b = random.sample(list, 2)
>>> a
'bannas'
>>> b
'grapes'

另一种选择是:如果你不在乎列表,我会用pop,如果你在乎,你可以复制一份,然后用pop(我不知道你想怎么用你的列表)。你知道吗

idx = random.randint(0,len(fruit_list))
a = fruit_list.pop(idx)

idx = random.randint(0,len(fruit_list))
b = fruit_list.pop(idx)

print(a + ' ' + b)

另一种方法是把你的单子搅乱,然后按顺序一个接一个地拣起来。你知道吗

random.shuffle(fruit_list)
a = fruit_list[0]
b = fruit_list[1]

print(a + ' ' + b)

使用流行音乐,再次:

random.shuffle(fruit_list)
a = fruit_list.pop()
b = fruit_list.pop()

print(a + ' ' + b)

相关问题 更多 >