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

ran*_*dme 3 python random

假设我有一份颜色列表,colours = ['red', 'blue', 'green', 'purple'].
然后我希望调用我希望存在的这个python函数random_object = random_choice(colours).现在,如果random_object持有'蓝色',我希望colours = ['red', 'green', 'purple'].

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

Rus*_*ove 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
Run Code Online (Sandbox Code Playgroud)


flo*_*low 6

单程:

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 )
Run Code Online (Sandbox Code Playgroud)