如何创建随机范围,但排除特定数字? [英] How do you create a random range, but exclude a specific number?
本文介绍了如何创建随机范围,但排除特定数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码:
while True:
if var_p1 != "0":
break
else:
import random
var_p1 = random.randint(-5,5)
我希望循环重复,直到 var_p1
等于零。但是,我一直都是零。我做错了什么?
I want the loop to repeat until var_p1
equals anything but zero. However, I get zero all the time. What am I doing wrong?
推荐答案
回答标题中的问题,而不是真正的问题(Daniel Roseman回答) :
Answering the question in the title, not the real problem (which was answered by Daniel Roseman):
如何创建随机范围,但排除特定数字?
使用 random.choice
:
import random
allowed_values = list(range(-5, 5+1))
allowed_values.remove(0)
# can be anything in {-5, ..., 5} \ {0}:
random_value = random.choice(allowed_values)
这篇关于如何创建随机范围,但排除特定数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文