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

3 投票
2 回答
9305 浏览
提问于 2025-04-16 04:34

假设我有一个颜色的列表,colours = ['red', 'blue', 'green', 'purple']
然后我想调用一个我希望存在的Python函数,random_object = random_choice(colours)
现在,如果random_object的值是'blue',我希望colours = ['red', 'green', 'purple']

Python里有这样的函数吗?

2 个回答

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

撰写回答