gpt4 book ai didi

Python - 从一个范围内随机抽样,同时避免某些值

转载 作者:太空宇宙 更新时间:2023-11-04 09:59:34 25 4
gpt4 key购买 nike

我一直在阅读 random 模块中的 random.sample() 函数,但没有看到任何解决我问题的方法。

我知道使用 random.sample(range(1,100),5) 会给我 5 个来自“人口”的独特样本......

我想在 range(0,999) 中得到一个随机数。我可以使用 random.sample(range(0,999),1) 但为什么我要考虑使用 random.sample()

我需要该范围内的随机数不匹配单独数组中的任何数字(例如,[443,122,738])

有没有相对简单的方法可以做到这一点?

此外,我对 python 还很陌生,绝对是初学者 -- 如果您希望我用我可能遗漏的任何信息更新问题,那么我会的。

编辑:不小心说了一次random.range()。糟糕。

最佳答案

实现此目的的一种方法是简单地检查数字,然后将其附加到列表中,然后您可以在列表中使用这些数字。

import random

non_match = [443, 122, 738]
match = []

while len(match) < 6: # Where 6 can be replaced with how many numbers you want minus 1
x = random.sample(range(0,999),1)
if x not in non_match:
match.append(x)

关于Python - 从一个范围内随机抽样,同时避免某些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com