假设我有一个颜色列表,colours = ['red', 'blue', 'green', 'purple']
。
然后我希望调用这个可能存在的Python函数:random_object = random_choice(colours)
。
现在,如果随机对象是'blue',我希望colours = ['red', 'green', 'purple']
。
Python中是否存在这样的函数?
random.shuffle()
。
random.choice()
会选择一个,但不会将其删除。import random
# this will choose one and remove it
def choose_and_remove( items ):
# pick an item index
if items:
index = random.randrange( len(items) )
return items.pop(index)
# nothing left!
return None
一种方法:
from random import shuffle
def walk_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 )