Python从随机列表中删除一个项

2024-05-08 19:30:58 发布

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

我该如何着手允许random.choice从列表中选择一个项目(一次、两次或三次),然后从列表中删除。

例如,它可以是1-10,在数字1被选取之后,在程序重置之前,不再允许1被选取

这是一个虚构的例子,用颜色和数字代替我的文字

colors = ["red","blue","orange","green"]
numbers = ["1","2","3","4","5"]
designs = ["stripes","dots","plaid"]

random.choice (colors)
if colors == "red":
    print ("red")
    random.choice (numbers)
    if numbers == "2":##Right here is where I want an item temporarily removed(stripes for example)
        random.choice (design)

我希望这能有所帮助,我正试图为我的实际项目保密=\n很抱歉给您带来不便

忘了在代码中提及,在红色被选中后,也需要删除


Tags: 项目程序列表if颜色数字randomred
1条回答
网友
1楼 · 发布于 2024-05-08 19:30:58

您可以使用random.choicelist.remove

from random import choice as rchoice

mylist = range(10)
while mylist:
    choice = rchoice(mylist)
    mylist.remove(choice)
    print choice

或者,正如@Henry Keiter所说,您可以使用random.shuffle

from random import shuffle

mylist = range(10)
shuffle(mylist)
while mylist:
    print mylist.pop()

如果在此之后仍需要重新排列列表,可以执行以下操作:

...
shuffle(mylist)
mylist2 = mylist
while mylist2:
    print mylist2.pop()

现在您将得到一个空列表mylist2,以及您的无序列表mylist

编辑 关于你发布的代码。你在写random.choice(colors),但是random.choice做什么呢?它选择随机答案并返回(!)它。所以你必须写

chosen_color = random.choice(colors)
if chosen_color == "red":
    print "The color is red!"
    colors.remove("red") ##Remove string from the list
    chosen_number = random.choice(numbers)
    if chosen_number == "2":
        chosen_design = random.choice(design)

相关问题 更多 >