Python被选中后,从随机列表中删除一个项目 [英] Python remove an item from a random list, after being picked

查看:353
本文介绍了Python被选中后,从随机列表中删除一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How would I go about allowing a random.choice to pick an item from a list(once, twice, or three times) and then be removed from the list.

例如,它可能是1-10,并且在选择数字1之后,不再允许选择1,直到重置程序为止

for example it could be 1-10 and the after the number 1 gets picked, no longer allow 1 to be picked until the program is reset

这是一个用颜色和数字代替我的单词的虚构示例

This is a made up example with colors and numbers replacing my words

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)

希望能对您有所帮助,我正在尝试将我的实际项目保密= \不便之处,敬请谅解

I hope that helps, I'm trying to keep my actual project a secret =\ sorry for the inconvenience

忘记了在代码中提及的内容,因为红色被选中后也需要删除

Forgot to mention in the code, after red gets picked that needs to be removed as well

推荐答案

您可以使用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

Or, as @Henry Keiter said, you can use random.shuffle

from random import shuffle

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

如果在此之后仍需要改组列表,则可以执行以下操作:

If you still need your shuffled list after that, you can do as follows:

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

现在,您将获得一个空列表 mylist2 ,以及经过改组的列表 mylist .

And now you will get an empty list mylist2, and your shuffled list mylist.

编辑 关于您发布的代码.您正在编写random.choice(colors),但是random.choice的作用是什么?它选择随机答案,然后返回(!).所以你必须写

EDIT About code you posted. You are writing random.choice(colors), but what random.choice does? It choices random answer and returns(!) it. So you have to write

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)

这篇关于Python被选中后,从随机列表中删除一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆