我正在尝试在 Python 中生成一个随机数,但我需要它包含某些数字。
假设我想要的范围是 100000 到 999999 之间,所以我希望它在该范围内,但也包括 1、4 和 5 等数字。
有办法做到这一点吗?
最佳答案
您可以逐位构建数字
>>> import random
>>> def fun(required=(),size=6):
result = list(required)
n = size-len(result)
result.extend( random.randint(0,10) for _ in range(n)) # fill in the remaining digits
random.shuffle(result)
assert any(result) #make sure that there is at least one non zero digit
while not result[0]: #make sure that the first digit is non zero so the resulting number be of the required size
random.shuffle(result)
return int("".join(map(str,result)))
>>> fun([1,4,5])
471505
>>> fun([1,4,5])
457310
>>> fun([1,4,5])
912457
>>> fun([1,4,5])
542961
>>> fun([1,4,5])
145079
>>>
关于Python随机模块: How can I generate a random number which includes certain digits?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70660733/