簡體   English   中英

如何從列表中選擇一個隨機元素並將其刪除?

[英]How can you select a random element from a list, and have it be removed?

假設我有一個顏色列表, colours = ['red', 'blue', 'green', 'purple']
然后我希望調用我希望存在的這個python函數, random_object = random_choice(colours) 現在,如果random_object持有'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 )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM