如何在python中生成具有特定长度的随机数

问题:如何在python中生成具有特定长度的随机数

假设我需要一个3位数的数字,因此它类似于:

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56

Let say I need a 3 digit number, so it would be something like:

>>> random(3)
563

or

>>> random(5)
26748
>> random(2)
56

回答 0

要获得一个随机的3位数字:

from random import randint
randint(100, 999)  # randint is inclusive at both ends

(假设您实际上是指三位数,而不是“最多三位数”。)

要使用任意数量的数字:

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(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

输出:

33
124
5127

To get a random 3-digit number:

from random import randint
randint(100, 999)  # randint is inclusive at both ends

(assuming you really meant three digits, rather than “up to three digits”.)

To use an arbitrary number of digits:

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(2)
print random_with_N_digits(3)
print random_with_N_digits(4)

Output:

33
124
5127

回答 1

如果要将其作为字符串(例如10位电话号码),可以使用以下命令:

n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])

If you want it as a string (for example, a 10-digit phone number) you can use this:

n = 10
''.join(["{}".format(randint(0, 9)) for num in range(0, n)])

回答 2

如果您需要一个3位数的数字并希望001-099是有效数字,则仍应使用randrange / randint,因为它比其他方法更快。转换为字符串时,只需在必要的前面加上零即可。

import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)

或者,如果您不想将随机数另存为int,则可以将其作为oneliner进行:

'{:03}'.format(random.randrange(1, 10**3))

python 3.6+只有oneliner:

f'{random.randrange(1, 10**3):03}'

上面的示例输出是:

  • ‘026’
  • ‘255’
  • ‘512’

实现为功能:

import random

def n_len_rand(len_, floor=1):
    top = 10**len_
    if floor > top:
        raise ValueError(f"Floor {floor} must be less than requested top {top}")
    return f'{random.randrange(floor, top):0{len_}}'

If you need a 3 digit number and want 001-099 to be valid numbers you should still use randrange/randint as it is quicker than alternatives. Just add the neccessary preceding zeros when converting to a string.

import random
num = random.randrange(1, 10**3)
# using format
num_with_zeros = '{:03}'.format(num)
# using string's zfill
num_with_zeros = str(num).zfill(3)

Alternatively if you don’t want to save the random number as an int you can just do it as a oneliner:

'{:03}'.format(random.randrange(1, 10**3))

python 3.6+ only oneliner:

f'{random.randrange(1, 10**3):03}'

Example outputs of the above are:

  • ‘026’
  • ‘255’
  • ‘512’

Implemented as a function:

import random

def n_len_rand(len_, floor=1):
    top = 10**len_
    if floor > top:
        raise ValueError(f"Floor {floor} must be less than requested top {top}")
    return f'{random.randrange(floor, top):0{len_}}'

回答 3

0是否算作可能的第一位数字?如果是这样,那么您需要random.randint(0,10**n-1)。如果没有,random.randint(10**(n-1),10**n-1)。如果永远不允许使用零,那么您将必须明确拒绝其中包含零的n random.randint(1,9)数字,或者绘制数字。

另外:有趣的是,randint(a,b)使用了一些非Python的“索引”来获取随机数a <= n <= b。有人可能希望它像这样工作range,并产生一个随机数a <= n < b。(请注意封闭的上限间隔。)

鉴于评论中的答复randrange,请注意可以用清洁剂代替它们random.randrange(0,10**n)random.randrange(10**(n-1),10**n)random.randrange(1,10)

Does 0 count as a possible first digit? If so, then you need random.randint(0,10**n-1). If not, random.randint(10**(n-1),10**n-1). And if zero is never allowed, then you’ll have to explicitly reject numbers with a zero in them, or draw n random.randint(1,9) numbers.

Aside: it is interesting that randint(a,b) uses somewhat non-pythonic “indexing” to get a random number a <= n <= b. One might have expected it to work like range, and produce a random number a <= n < b. (Note the closed upper interval.)

Given the responses in the comments about randrange, note that these can be replaced with the cleaner random.randrange(0,10**n), random.randrange(10**(n-1),10**n) and random.randrange(1,10).


回答 4

您可以为自己编写一个小函数来执行所需的操作:

import random
def randomDigits(digits):
    lower = 10**(digits-1)
    upper = 10**digits - 1
    return random.randint(lower, upper)

基本上,10**(digits-1)为您提供最小的{digit}位数字,并10**digits - 1为您提供最大的{digit}位数字(恰好是最小的{digit + 1}位数字减去1!)。然后,我们只是从该范围取一个随机整数。

You could write yourself a little function to do what you want:

import random
def randomDigits(digits):
    lower = 10**(digits-1)
    upper = 10**digits - 1
    return random.randint(lower, upper)

Basically, 10**(digits-1) gives you the smallest {digit}-digit number, and 10**digits - 1 gives you the largest {digit}-digit number (which happens to be the smallest {digit+1}-digit number minus 1!). Then we just take a random integer from that range.


回答 5

我真的很喜欢RichieHindle的答案,但是我很喜欢这个问题作为练习。这是使用字符串的蛮力实现:)

import random
first = random.randint(1,9)
first = str(first)
n = 5

nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs))    :
    first += str(nrs[i])

print str(first)

I really liked the answer of RichieHindle, however I liked the question as an exercise. Here’s a brute force implementation using strings:)

import random
first = random.randint(1,9)
first = str(first)
n = 5

nrs = [str(random.randrange(10)) for i in range(n-1)]
for i in range(len(nrs))    :
    first += str(nrs[i])

print str(first)

回答 6

官方文档来看,sample()方法似乎不适合此目的吗?

import random

def random_digits(n):
    num = range(0, 10)
    lst = random.sample(num, n)
    print str(lst).strip('[]')

输出:

>>>random_digits(5)
2, 5, 1, 0, 4

From the official documentation, does it not seem that the sample() method is appropriate for this purpose?

import random

def random_digits(n):
    num = range(0, 10)
    lst = random.sample(num, n)
    print str(lst).strip('[]')

Output:

>>>random_digits(5)
2, 5, 1, 0, 4

回答 7

您可以创建一个使用int列表,将字符串转换为连接并再次转换为int的函数,如下所示:

import random

def generate_random_number(length):
    return int(''.join([str(random.randint(0,10)) for _ in range(length)]))

You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:

import random

def generate_random_number(length):
    return int(''.join([str(random.randint(0,10)) for _ in range(length)]))