首页 > 解决方案 > 生成一个随机数,如果不符合条件则重新生成。怎么做?

问题描述

我是一名新手,目前正在学习在线 python 课程。

    # Generate Number 1
from random import choices
population = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
weights = [0.11, 0.10, 0.14, 0.09, 0.13, 0.03, 0.08, 0.07, 0.09, 0.02, 0.03]
number1 = choices(population, weights)


# Generate Number 2
population2 = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
weights2 = [0.03, 0.07, 0.05, 0.05, 0.09, 0.04, 0.06, 0.07, 0.02, 0.04, 0.04, 0.05, 0.03, 0.05, 0.01, 0.04]
number2 = choices(population2, weights2)

if number1[0] + 1 < number2[0] < number1[0] + 12 :
    print(number1 + number2)
else :

借助本网站上的一些帖子,我能够生成 2 个具有各自权重的随机数。

如果if语句上的条件不正确,我想告诉程序继续生成数字 2 直到满足这样的条件。我的问题是我不知道该研究什么。

有人可以给我一个提示我必须学习什么吗?例如“查看For循环或xpython 函数”。我希望我可以自己研究和解决,而不是让别人直接告诉我该怎么做。

这篇文章对我有帮助吗?

如果不等于 x,则再次生成随机数

使用 2020.3 社区版 PyCharm

感谢您的帮助和时间。

标签: pythonpython-3.x

解决方案


好吧,我想说一种学习方法是获取一个您不知道它做什么的代码,除了输出是您想要的,因此您尝试逐部分分解它以了解其含义。

也许你可以阅读之后。但是阅读你不知道的事情往往效率不高。

所以我没有根据我刚刚写的内容来解释我的答案;)

from random import choices

population = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
weights = [0.11, 0.10, 0.14, 0.09, 0.13, 0.03, 0.08, 0.07, 0.09, 0.02, 0.03]

population2 = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
weights2 = [0.03, 0.07, 0.05, 0.05, 0.09, 0.04, 0.06, 0.07, 0.02, 0.04, 0.04, 0.05, 0.03, 0.05, 0.01, 0.04]

while True:
    number1 = choices(population, weights)
    number2 = choices(population2, weights2)

    if number1[0] + 1 < number2[0] < number1[0] + 12 :
        print (number1 + number2)
        break
    else:
        pass

推荐阅读