python - 生成一个随机数,如果不符合条件则重新生成。怎么做?
问题描述
我是一名新手,目前正在学习在线 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
循环或x
python 函数”。我希望我可以自己研究和解决,而不是让别人直接告诉我该怎么做。
这篇文章对我有帮助吗?
使用 2020.3 社区版 PyCharm
感谢您的帮助和时间。
解决方案
好吧,我想说一种学习方法是获取一个您不知道它做什么的代码,除了输出是您想要的,因此您尝试逐部分分解它以了解其含义。
也许你可以阅读之后。但是阅读你不知道的事情往往效率不高。
所以我没有根据我刚刚写的内容来解释我的答案;)
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
推荐阅读
- c++ - constexpr 函数中的非文字(通过 std::is_constant_evaluate)
- javascript - 搜索使用异步存储存储的项目
- .net-core - 为什么在 vs 代码(.NET Core)中调试时不构建 C# 代码?
- flutter - 如何在 Flutter 中像 Youtube 一样显示时间
- python - CV2 在编译成 EXE 时抛出错误,而不是在自编译时
- mysql - 如何将约束添加到 MYSQL 中的列仅以保存已存在于同一表的另一列中的值?
- computer-vision - 从图像匹配路线图
- ruby-on-rails - Rails 模型只接受 0 到 1 之间的浮点数
- java - 用于员工经理搜索的二叉搜索树
- c++ - 是否可以在编译时初始化数组,以便在运行时不需要时间?