且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-05 16:38:47

首先,如果由于要一次又一次地删除它而希望将其删除,则可能要在随机模块中使用random.shuffle().

Firstly, if you want it removed because you want to do this again and again, you might want to use random.shuffle() in the random module.

random.choice()选择一个,但不会将其删除.

random.choice() picks one, but does not remove it.

否则,请尝试:

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