如何从列表中随机选择一个元素并将其删除?

3

假设我有一个颜色列表,colours = ['red', 'blue', 'green', 'purple']
然后我希望调用这个可能存在的Python函数:random_object = random_choice(colours)。 现在,如果随机对象是'blue',我希望colours = ['red', 'green', 'purple']

Python中是否存在这样的函数?

2个回答

8
首先,如果你想删除它是因为你想一遍又一遍地这样做,你可能想在随机模块中使用 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

7

一种方法:

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 )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接