Python随机函数从值列表中选择一个新项目 [英] Python random function to select a new item from a list of values

查看:61
本文介绍了Python随机函数从值列表中选择一个新项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 Python 中的值列表中获取随机数.我尝试使用 random.choice() 函数,但它有时会连续返回相同的值.我想每次都从列表中返回新的随机值.Python 中是否有任何函数可以让我执行这样的操作?

I need to fetch random numbers from a list of values in Python. I tried using random.choice() function but it sometimes returns same values consecutively. I want to return new random values from the list each time. Is there any function in Python that allows me to perform such an action ?

推荐答案

创建列表的副本,将其打乱,然后在需要新的随机值时从列表中一一弹出:

Create a copy of the list, shuffle it, then pop items from that one by one as you need a new random value:

shuffled = origlist[:]
random.shuffle(shuffled)

def produce_random_value():
    return shuffled.pop()

这保证不会重复元素.但是,您可以选择用完的数字,此时您可以再次复制并重新洗牌.

This is guaranteed to not repeat elements. You can, however, run out of numbers to pick, at which point you could copy again and re-shuffle.

要连续执行此操作,您可以将其设为生成器函数:

To do this continuously, you could make this a generator function:

def produce_randomly_from(items):
    while True:
        shuffled = list(items)
        random.shuffle(shuffled)
        while shuffled:
            yield shuffled.pop()

然后在循环中使用它或使用 next() 函数获取一个新值:

then use this in a loop or grab a new value with the next() function:

random_items = produce_randomly_from(inputsequence)
# grab one random value from the sequence
random_item = next(random_items)

这篇关于Python随机函数从值列表中选择一个新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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