在Python中是否有一种简单的方法可以生成一个范围内的随机数,但不包括该范围内的某些数字子集?
例如,我知道您可以生成0到9之间的随机数:
from random import randint
randint(0,9)
Run Code Online (Sandbox Code Playgroud)
如果我有一个列表,例如exclude=[2,5,7]我不想被退回怎么办?
McG*_*ady 14
试试这个:
from random import choice
print choice([i for i in range(0,9) if i not in [2,5,7]])
Run Code Online (Sandbox Code Playgroud)
Try with something like this:
from random import randint
def my_custom_random():
exclude=[2,5,7]
randInt = randint(0,9)
return my_custom_random() if randInt in exclude else randInt
print(my_custom_random())
Run Code Online (Sandbox Code Playgroud)
如果您有更大的列表,我建议使用集合操作,因为它们比推荐的答案明显更快。
random.choice(list(set([x for x in range(0, 9)]) - set(to_exclude)))
Run Code Online (Sandbox Code Playgroud)
我对接受的答案和上面的代码进行了一些测试。
对于每个测试,我进行了 50 次迭代并测量了平均时间。为了进行测试,我使用了 999999 的范围。
to_exclude 大小 10 个元素:
接受的答案 = 0.1782s
此答案 = 0.0953s
to_exclude 大小 100 个元素:
接受的答案 = 01.2353s
此答案 = 00.1117s
to_exclude 大小 1000 个元素:
接受的答案 = 10.4576s
此答案 = 00.1009s