在 Python 3 中循环一组 if/else 语句,直到列表变量具有三个唯一值
尝试重复这一段 python 代码,直到得到三个不同的结果。这不是实际的代码,只是执行相同操作的简化版本。
roll = random.randint(1,100)
if roll < 10:
name += "alpha"
elif roll < 37:
name += "bravo"
elif roll < 50:
name += "charlie"
elif roll < 89:
name += "delta"
else:
name += "echo"
print(name)
基本上,我希望这段代码不断重复,直到 [name] 具有三个不同的值,然后我希望输出列出所有三个值,每个值都在一个新行上。我不确定做到这一点的最佳方法是什么。感谢您的任何帮助
编辑:在我的实际代码中,每个数字的范围并不是均匀分布的。我编辑了上面的内容来反映这一点。由于获得五个可能结果的机会不同,因此 random.sample 将不起作用(除非它可以针对每个结果的不同赔率进行格式化)
Trying to make this section of python code repeat until it gets three different results. This isn't the actual code, just a simplified version that does the same thing.
roll = random.randint(1,100)
if roll < 10:
name += "alpha"
elif roll < 37:
name += "bravo"
elif roll < 50:
name += "charlie"
elif roll < 89:
name += "delta"
else:
name += "echo"
print(name)
Basically, I want this segment of code to continuously repeat until [name] has three different values, and then I want the output to list all three values, each on a new line. I'm not sure what the best way to do this would be. Thanks for any helpn
edit: in my actual code, the ranges for each number aren't evenly distributed. I edited the above to reflect this. Since the chance at getting each of the five possible results is different, random.sample won't work (unless it can be formatted for different odds on each result)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
对于这个例子,我会这样做:
For this example, I'd do this:
制作一个列表,然后循环,直到其中包含三个唯一的项目。
Make a list and then loop until you have three unique items in it.
如果您需要唯一的值,也许
set
类型就是您所需要的。If you need unique values, perhaps the
set
type is what you're after.random.sample 有什么问题?
编辑:
What is wrong with random.sample?
EDIT: