如何从列表中选择一个不同于上一个的随机整数?

2024-04-26 06:59:14 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个整数列表如下:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

我想用choice从中选择随机整数:

item = random.choice(list)

但我如何确保下次我这样做,它是不同的项目?我不想从列表中删除项目。你知道吗


Tags: 项目列表整数randomitemlistchoice
3条回答

创建从上一个生成的选项进行检查的生成器:

import random
def randomNotPrevious(l):
    prev = None
    while True:
        choice =  random.choice(l)
        if choice != prev:
            prev = choice
            yield choice

>>> l = [1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> randomLst = randomNotPrevious(l)
>>> next(randomLst)
1
>>> next(randomLst)
5
>>> next(randomLst)
3
>>> next(randomLst)
6
>>> next(randomLst)
5

如果您无论如何都需要它们,只是希望它们以随机顺序排列(但您不想更改列表),或者如果您对要采样的项目数没有上限(列表大小除外):

import random
def random_order(some_list):
    order = list(range(len(some_list)))
    random.shuffle(order)
    for i in order:
        yield some_list[i]

my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

for item in random_order(my_list):
    ... # do stuff

或者,您可以这样使用:

order = random_order(my_list)
some_item = next(order)
some_item = next(order)
...

如果要从列表中获得不同的随机值,请使用random.sample(list, n)。你知道吗

相关问题 更多 >