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

Python:如何生成12位随机数?,第1张

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

一种简单的方法怎么了?

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

而且,如果您希望以前导零开头,则需要一个字符串。

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

编辑:

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

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5640108.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存