Python:如何生成一个 12 位随机数?

标签 python

在Python中,如何生成一个12位的随机数?有没有我们可以指定范围的函数,比如 random.range(12)

import random
random.randint()

输出应该是一个包含 0-9 范围内的 12 位数字的字符串(允许前导零)。

最佳答案

直截了当的方法有什么问题?

>>> import random
>>> random.randint(100000000000,999999999999)
544234865004L

如果您希望它带有前导零,则需要一个字符串。

>>> "%0.12d" % random.randint(0,999999999999)
'023432326286'

编辑:

我自己对这个问题的解决方案是这样的:

import random

def rand_x_digit_num(x, leading_zeroes=True):
    """Return an X digit number, leading_zeroes returns a string, otherwise int"""
    if not leading_zeroes:
        # wrap with str() for uniform results
        return random.randint(10**(x-1), 10**x-1)  
    else:
        if x > 6000:
            return ''.join([str(random.randint(0, 9)) for i in xrange(x)])
        else:
            return '{0:0{x}d}'.format(random.randint(0, 10**x-1), x=x)

测试结果:

>>> rand_x_digit_num(5)
'97225'
>>> rand_x_digit_num(5, False)
15470
>>> rand_x_digit_num(10)
'8273890244'
>>> rand_x_digit_num(10)
'0019234207'
>>> rand_x_digit_num(10, False)
9140630927L

速度的计时方法:

def timer(x):
        s1 = datetime.now()
        a = ''.join([str(random.randint(0, 9)) for i in xrange(x)])
        e1 = datetime.now()
        s2 = datetime.now()
        b = str("%0." + str(x) + "d") % random.randint(0, 10**x-1)
        e2 = datetime.now()
        print "a took %s, b took %s" % (e1-s1, e2-s2)

速度测试结果:

>>> timer(1000)
a took 0:00:00.002000, b took 0:00:00
>>> timer(10000)
a took 0:00:00.021000, b took 0:00:00.064000
>>> timer(100000)
a took 0:00:00.409000, b took 0:00:04.643000
>>> timer(6000)
a took 0:00:00.013000, b took 0:00:00.012000
>>> timer(2000)
a took 0:00:00.004000, b took 0:00:00.001000

它告诉我们什么:

对于长度低于 6000 个字符的任何数字,我的方法更快 - 有时快得多,但对于更大的数字,arshajii 建议的方法看起来更好。

关于Python:如何生成一个 12 位随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13496087/

相关文章:

python - 如何在python中的感兴趣区域周围绘制一个矩形

python - 压缩 numpy 数组的有效方法(python)

python - 如何使用 pyplot 在相同的 x 轴(日期时间)但不同的 y 轴上绘制折线图和条形图?

python - 如何按 MultiIndex 和按值对 Pandas DataFrame 进行排序?

python - 使用 Beautiful Soup 获取源代码中的完整 URL

python - 黑窗pygame

python - 使用 .Replace 时创建新行

python - Django 'User' 对象不可迭代

python - 如何检查 PyQt5 在 Mac 上是否正确安装?

python - Pandas 事件研究