How Can You Select A Random Element From A List, And Have It Be Removed?
Let's say I have a list of colours, colours = ['red', 'blue', 'green', 'purple']. I then wish to call this python function that I hope exists, random_object = random_choice(colours
Solution 1:
Firstly, if you want it removed because you want to do this again and again, you might want to use random.shuffle()
in the random module.
random.choice()
picks one, but does not remove it.
Otherwise, try:
import random
# this will choose one and remove itdefchoose_and_remove( items ):
# pick an item indexif items:
index = random.randrange( len(items) )
return items.pop(index)
# nothing left!returnNone
Solution 2:
one way:
from random import shuffle
defwalk_random_colors( colors ):
# optionally make a copy first:# colors = colors[:]
shuffle( colors )
while colors:
yield colors.pop()
colors = [ ... whatever ... ]
for color in walk_random_colors( colors ):
print( color )
Post a Comment for "How Can You Select A Random Element From A List, And Have It Be Removed?"