18

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

import random
random.randint()

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

4

6 回答 6

38

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

>>> 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建议的方法看起来更好。

于 2012-11-21T15:14:30.697 回答
5

random.randrange(10**11, 10**12)。它就像randint遇见一样工作range

从文档中:

randrange(self, start, stop=None, step=1, int=<type 'int'>, default=None, maxwidth=9007199254740992L) method of random.Random instance
    Choose a random item from range(start, stop[, step]).

    This fixes the problem with randint() which includes the
    endpoint; in Python this is usually not what you want.
    Do not supply the 'int', 'default', and 'maxwidth' arguments.

这实际上就像做random.choice(range(10**11, 10**12))or random.randint(10**1, 10**12-1)。由于它符合与 相同的语法range(),因此它比这两个替代方案更直观、更简洁

如果允许前导零:

"%012d" %random.randrange(10**12)
于 2012-11-21T15:08:01.823 回答
4

由于允许前导零(根据您的评论),您还可以使用:

int(''.join(str(random.randint(0,9)) for _ in xrange(12)))

编辑:当然,如果你想要一个字符串,你可以省略int部分:

''.join(str(random.randint(0,9)) for _ in xrange(12))

在我看来,这似乎是最直接的方法。

于 2012-11-21T15:14:30.373 回答
2

有很多方法可以做到这一点:

import random

rnumber1 = random.randint(10**11, 10**12-1) # randint includes endpoint
rnumber2 = random.randrange(10**11, 10**12) # randrange does not

# useful if you want to generate some random string from your choice of characters
digits = "123456789"
digits_with_zero = digits + "0"

rnumber3 = random.choice(digits) + ''.join(random.choice(digits_with_zero) for _ in range(11))
于 2012-11-21T15:13:28.327 回答
1

这可能不是您正在寻找的,但是像rstr这样的库可以让您生成随机字符串。有了这个,你所需要的就是(允许前导 0):

import rstr
foo = rstr.digits(12)
于 2012-11-21T15:19:34.963 回答
1
from random import randint

def random_with_N_digits(n):
    range_start = 10**(n-1)
    range_end = (10**n)-1
    return randint(range_start, range_end)

print random_with_N_digits(12)
于 2012-11-21T15:10:03.330 回答