python生成四位随机数

时间:2021-12-12 14:35:43

有些时候需要发送短信给用户生成四位随机数字,这里在python中我们可以根据python自带的标准库random和string来实现。

  • random下有三个可以随机取数的函数,分别是choice,choices,sample
 # random.choice
def choice(self, seq):
"""Choose a random element from a non-empty sequence."""
try:
i = self._randbelow(len(seq))
except ValueError:
raise IndexError('Cannot choose from an empty sequence') from None
return seq[i]
 # random.choices
def choices(self, population, weights=None, *, cum_weights=None, k=1):
"""Return a k sized list of population elements chosen with replacement. If the relative weights or cumulative weights are not specified,
the selections are made with equal probability. """
random = self.random
if cum_weights is None:
if weights is None:
_int = int
total = len(population)
return [population[_int(random() * total)] for i in range(k)]
cum_weights = list(_itertools.accumulate(weights))
elif weights is not None:
raise TypeError('Cannot specify both weights and cumulative weights')
if len(cum_weights) != len(population):
raise ValueError('The number of weights does not match the population')
bisect = _bisect.bisect
total = cum_weights[-1]
hi = len(cum_weights) - 1
return [population[bisect(cum_weights, random() * total, 0, hi)]
for i in range(k)]
 # random.sample

 def sample(self, population, k):
"""Chooses k unique random elements from a population sequence or set. Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices). Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample. To choose a sample in a range of integers, use range as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(range(10000000), 60)
""" # Sampling without replacement entails tracking either potential
# selections (the pool) in a list or previous selections in a set. # When the number of selections is small compared to the
# population, then tracking selections is efficient, requiring
# only a small set and an occasional reselection. For
# a larger number of selections, the pool tracking method is
# preferred since the list takes less space than the
# set and it doesn't suffer from frequent reselections. if isinstance(population, _Set):
population = tuple(population)
if not isinstance(population, _Sequence):
raise TypeError("Population must be a sequence or set. For dicts, use list(d).")
randbelow = self._randbelow
n = len(population)
if not 0 <= k <= n:
raise ValueError("Sample larger than population or is negative")
result = [None] * k
setsize = 21 # size of a small set minus size of an empty list
if k > 5:
setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
if n <= setsize:
# An n-length list is smaller than a k-length set
pool = list(population)
for i in range(k): # invariant: non-selected at [0,n-i)
j = randbelow(n-i)
result[i] = pool[j]
pool[j] = pool[n-i-1] # move non-selected item into vacancy
else:
selected = set()
selected_add = selected.add
for i in range(k):
j = randbelow(n)
while j in selected:
j = randbelow(n)
selected_add(j)
result[i] = population[j]
return result

从上面这三个函数看来,都可以在给定的一个数字集内随机产生四位数字。三种方法如下:

 import string
import random # 方法一
seeds = string.digits
random_str = []
for i in range(4):
random_str.append(random.choice(seeds))
print("".join(random_str)) # 方法二
seeds = string.digits
random_str = random.choices(seeds, k=4)
print("".join(random_str)) # 方法三
seeds = string.digits
random_str = random.sample(seeds, k=4)
print("".join(random_str))
  • 说明一下:string.digits是一个定义好的数字字符串,就是从"0123456789"。
 """
whitespace -- a string containing all ASCII whitespace
ascii_lowercase -- a string containing all ASCII lowercase letters
ascii_uppercase -- a string containing all ASCII uppercase letters
ascii_letters -- a string containing all ASCII letters
digits -- a string containing all ASCII decimal digits
hexdigits -- a string containing all ASCII hexadecimal digits
octdigits -- a string containing all ASCII octal digits
punctuation -- a string containing all ASCII punctuation characters
printable -- a string containing all ASCII characters considered printable
""" # Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_letters = ascii_lowercase + ascii_uppercase
digits = ''
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = ''
punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + ascii_letters + punctuation + whitespace

上述三种方式虽说都可以生成随机数,但是choice和choices随机取得数字是可重复的,而sample方法的随机数是不会重复的。这个是他们之间的区别之一。