如何从列表中选择一个随机元素并将其删除? [英] How can you select a random element from a list, and have it be removed?

查看:1099
本文介绍了如何从列表中选择一个随机元素并将其删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let's say I have a list of colours, colours = ['red', 'blue', 'green', 'purple'].
I then wish to call this python function that I hope exists, random_object = random_choice(colours). Now, if random_object holds 'blue', I hope colours = ['red', 'green', 'purple'].

这样的功能在python中存在吗?

Does such a function exist in python?

推荐答案

首先,如果由于要一次又一次地删除它而希望将其删除,则可能要在随机模块中使用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

这篇关于如何从列表中选择一个随机元素并将其删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆