Python remove an item from a random list, after be

2019-02-16 03:32发布

问题:

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.

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

回答1:

You can use random.choice and list.remove

from random import choice as rchoice

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

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()

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

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 random