Skip to main content
 首页 » 编程设计

python之如何获取不在整数黑名单中的随机数

2025年05月04日21虾米哥

我希望能够获得随机整数,但我的 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 
... 

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

请您参考如下方法:

不是重新采样,而是从预先准备好的数据中采样,黑名单项目已经被删除:

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