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

  • random下有三个可以随机取数的函数,分别是choice,choices,sample
1 # random.choice
2 def choice(self, seq):
3         """Choose a random element from a non-empty sequence."""
4         try:
5             i = self._randbelow(len(seq))
6         except ValueError:
7             raise IndexError('Cannot choose from an empty sequence') from None
8         return seq[i]

 1 # random.choices
 2 def choices(self, population, weights=None, *, cum_weights=None, k=1):
 3         """Return a k sized list of population elements chosen with replacement.
 4
 5         If the relative weights or cumulative weights are not specified,
 6         the selections are made with equal probability.
 7
 8         """
 9         random = self.random
10         if cum_weights is None:
11             if weights is None:
12                 _int = int
13                 total = len(population)
14                 return [population[_int(random() * total)] for i in range(k)]
15             cum_weights = list(_itertools.accumulate(weights))
16         elif weights is not None:
17             raise TypeError('Cannot specify both weights and cumulative weights')
18         if len(cum_weights) != len(population):
19             raise ValueError('The number of weights does not match the population')
20         bisect = _bisect.bisect
21         total = cum_weights[-1]
22         hi = len(cum_weights) - 1
23         return [population[bisect(cum_weights, random() * total, 0, hi)]
24                 for i in range(k)]

 1 # random.sample
 2
 3 def sample(self, population, k):
 4         """Chooses k unique random elements from a population sequence or set.
 5
 6         Returns a new list containing elements from the population while
 7         leaving the original population unchanged.  The resulting list is
 8         in selection order so that all sub-slices will also be valid random
 9         samples.  This allows raffle winners (the sample) to be partitioned
10         into grand prize and second place winners (the subslices).
11
12         Members of the population need not be hashable or unique.  If the
13         population contains repeats, then each occurrence is a possible
14         selection in the sample.
15
16         To choose a sample in a range of integers, use range as an argument.
17         This is especially fast and space efficient for sampling from a
18         large population:   sample(range(10000000), 60)
19         """
20
21         # Sampling without replacement entails tracking either potential
22         # selections (the pool) in a list or previous selections in a set.
23
24         # When the number of selections is small compared to the
25         # population, then tracking selections is efficient, requiring
26         # only a small set and an occasional reselection.  For
27         # a larger number of selections, the pool tracking method is
28         # preferred since the list takes less space than the
29         # set and it doesn't suffer from frequent reselections.
30
31         if isinstance(population, _Set):
32             population = tuple(population)
33         if not isinstance(population, _Sequence):
34             raise TypeError("Population must be a sequence or set.  For dicts, use list(d).")
35         randbelow = self._randbelow
36         n = len(population)
37         if not 0 <= k <= n:
38             raise ValueError("Sample larger than population or is negative")
39         result = [None] * k
40         setsize = 21        # size of a small set minus size of an empty list
41         if k > 5:
42             setsize += 4 ** _ceil(_log(k * 3, 4)) # table size for big sets
43         if n <= setsize:
44             # An n-length list is smaller than a k-length set
45             pool = list(population)
46             for i in range(k):         # invariant:  non-selected at [0,n-i)
47                 j = randbelow(n-i)
48                 result[i] = pool[j]
49                 pool[j] = pool[n-i-1]   # move non-selected item into vacancy
50         else:
51             selected = set()
52             selected_add = selected.add
53             for i in range(k):
54                 j = randbelow(n)
55                 while j in selected:
56                     j = randbelow(n)
57                 selected_add(j)
58                 result[i] = population[j]
59         return result

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

 1 import string
 2 import random
 3
 4 # 方法一
 5 seeds = string.digits
 6 random_str = []
 7 for i in range(4):
 8     random_str.append(random.choice(seeds))
 9 print("".join(random_str))
10
11 # 方法二
12 seeds = string.digits
13 random_str = random.choices(seeds, k=4)
14 print("".join(random_str))
15
16 # 方法三
17 seeds = string.digits
18 random_str = random.sample(seeds, k=4)
19 print("".join(random_str))

  • 说明一下:string.digits是一个定义好的数字字符串,就是从"0123456789"。
 1 """
 2 whitespace -- a string containing all ASCII whitespace
 3 ascii_lowercase -- a string containing all ASCII lowercase letters
 4 ascii_uppercase -- a string containing all ASCII uppercase letters
 5 ascii_letters -- a string containing all ASCII letters
 6 digits -- a string containing all ASCII decimal digits
 7 hexdigits -- a string containing all ASCII hexadecimal digits
 8 octdigits -- a string containing all ASCII octal digits
 9 punctuation -- a string containing all ASCII punctuation characters
10 printable -- a string containing all ASCII characters considered printable
11 """
12
13 # Some strings for ctype-style character classification
14 whitespace = ' \t\n\r\v\f'
15 ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
16 ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
17 ascii_letters = ascii_lowercase + ascii_uppercase
18 digits = '0123456789'
19 hexdigits = digits + 'abcdef' + 'ABCDEF'
20 octdigits = '01234567'
21 punctuation = r"""!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
22 printable = digits + ascii_letters + punctuation + whitespace

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

转载于:https://www.cnblogs.com/cpl9412290130/p/10259342.html

python生成四位随机数相关推荐

  1. c语言生成1000 9999随机数,python生成四位随机数

    有些时候需要发送短信给用户生成四位随机数字,这里在python中我们可以根据python自带的标准库random和string来实现. random下有三个可以随机取数的函数,分别是choice,ch ...

  2. python生成四位随机数_如何使用Python生成4位密码随机数

    如果您在Python 3.6中生成PIN码,请使用n = secrets.choice(range(1000, 10000));然后format(n, '04'),然后过滤掉不需要的组合. 如果你被P ...

  3. python生成四位随机数_python_产生4位的随机数(四位验证码)

    #思路从str1中随机取出4个字符之后拼接到一起 str1 = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM' imp ...

  4. php随机数四位,生成四位随机数的PHP代码

    纯数字的四位随机数 rand(1000,9999) 数字和字符混搭的四位随机字符串: function GetRandStr($len) { $chars = array( "a" ...

  5. js 生成四位随机数

    js生成四位随机数 <script>var charactors="1234567890"; var value='',i; for(j=1;j<=4;j++){ ...

  6. python加四位随机数_python生成四位随机数

    有些时候需要发送短信给用户生成四位随机数字,这里在python中我们可以根据python自带的标准库random和string来实现. random下有三个可以随机取数的函数,分别是choice,ch ...

  7. python生成规定随机数_python生成随机数的方法

    python生成随机数的方法 发布时间:2020-08-21 14:50:04 来源:亿速云 阅读:110 作者:小新 这篇文章主要介绍了python生成随机数的方法,具有一定借鉴价值,需要的朋友可以 ...

  8. python生成泊松分布随机数_生成满足泊松分布的随机数,以及python实现

    泊松分布是一个离散型随机变量分布,其分布律是: image 其中参数λ是单位时间(或单位面积)内随机事件的数学期望. k是随机事件发生的个数 泊松分布适合于描述单位时间内随机事件发生的次数的概率分布. ...

  9. Python生成前缀+随机数

    Python中生成随机数使用的是random函数 具体生成前缀不变,后面数字随机方法代码如下: import random import string def a(start='前缀'):ran_st ...

最新文章

  1. Linux下Tomcat重新启动
  2. python 变量传值传引用 区分
  3. Python入门100题 | 第072题
  4. 微软为何痛失移动操作系统?
  5. 【bzoj4195】[Noi2015]程序自动分析 离散化+并查集
  6. Android uevent
  7. Gradle学习之使用java plugin
  8. MATLAB生成正弦波
  9. Actor编程模型——Erlang/OTP
  10. JavaScript类数组对象参考
  11. selenium webdirver之ruby-开发ide乱码解决方案
  12. QT SQL使用指南
  13. 炸了炸了~翻译器中的王者,科大讯飞翻译器2.0横空出世!| 钛空智慧星球推荐...
  14. 设计分享 | STM32F103RCT6利用ULN2003驱动步进电机正反转
  15. Docker Study Note
  16. 阿里安全潘多拉实验室首先完美越狱苹果iOS 11.2
  17. 说企业自研应用是误区的,非蠢即坏
  18. Linux 删除指定目录下指定后缀名的所有文件
  19. 2021牛客多校#4 E-Tree Xor
  20. matlab函数merge_MATLAB数据合并方法

热门文章

  1. 【木头小开发】-iOS小小里程总结一二
  2. ubuntu 16.04 搭建 python 开发环境
  3. UVA10474 Where is the Marble?
  4. word文档老是出现这个提示-----“发现二义性的名称:TmpDDE”错误
  5. java线程安全问题之静态变量、实例变量、局部变量
  6. javascript 之---正则表达式
  7. 在颜值上,我 Bootstrap 真的没怕过谁
  8. ansible普通用户部署K8s要点
  9. MySQL分组函数使用的其他注意事项
  10. 事务注解 @Transactional