Python随机模块: How can I generate a random number which includes certain digits?

标签 python random numbers

我正在尝试在 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/

相关文章:

php - 在 mysql 中只返回一次随机行

c++ - 随机数生成器和线程安全

java - 如何从一定范围内生成4个不重复的数字?

linux - 获取指定端口的连接数

javascript - 数数错误

python - 如何在 pandas 中查询 MultiIndex 索引列的值

python - 在正数前加一个加号?

python - 带有通配符的 Scrapy 选择 id

python - python 上的迭代最近点 (ICP) 实现

java - 在 Java 中为 android 生成相同的随机 BigInteger