如何获得一个不在整数黑名单中的随机数?

2024-05-14 06:17:12 发布

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

我希望能够得到除blacklist数组中的数字以外的随机整数,我在理解如何再次迭代代码直到它找到正确的数字时遇到了一些困难。在

Python

def viewName(...):
    random_int = random.randint(0, 11)
    blacklist = [1, 2, 3, 5, 6, 10]

    for bl in blacklist:
        if random_int == bl:
            #try again till there's a number that isn't in the blacklist
        else:
            correctNumber = random_int
...

这看起来很基本,但我不明白如何反复迭代,直到有一个好的数字,什么是最快和更有效的方法来实现这一点,有什么建议吗?在


Tags: 代码inforifdef数字整数random
2条回答

不要重新取样,只需从预先准备好的数据中取样,并将黑名单项目删除:

import random

choices = list(set(range(12)).difference(blacklist))
n = random.choice(choices)

在python中没有do…while。我会做以下事情:

def viewName(...):
    blacklist = [1, 2, 3, 5, 6, 10]
    random_int = 1
    while random_int in blacklist:
        random_int = random.randint(0, 11)

相关问题 更多 >