有些时候需要发送短信给用户生成四位随机数字,这里在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方法的随机数是不会重复的。这个是他们之间的区别之一。

标签:random,population,weights,string,digits,containing,ASCII

来源: https://www.cnblogs.com/cpl9412290130/p/10259342.html

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

  1. python随机数生成的方法_python生成随机数的方法

    一.概述 python可以通过random包来产生随机数或者执行一些随机操作. 1. random.seed() 给定一个数据作为随机数种子,和大多数语言一样,python也可以使用时间来作为随机数种 ...

  2. python random.seed()函数 (生成固定随机数)random.seed(None)(取消固定随机数种子)

    我们调用 random.random() 生成随机数时,每一次生成的数都是随机的. 但是,当我们预先使用 random.seed(x) 设定好种子之后,其中的 x 可以是任意数字,如10,这个时候,先 ...

  3. python 随机数_Python中的随机数

    Python定义了一组用于生成或操纵随机数的函数.这种特殊类型的功能用于许多游戏,彩票或需要随机数生成的任何应用程序中. 随机数运算: 1.choice():此函数用于从容器生成1个随机数. 2.ra ...

  4. C#产生随机数之一 生成真随机数

    Random 成员 名称 ● 说明 Equals ● 确定指定的 Object 是否等于当前的 Object.(继承自 Object.) Finalize ● 允许Object 在"垃圾回收 ...

  5. python设定数值范围_Python 生成周期性波动的数据 可指定数值范围

    代码 import numpy as np import math import matplotlib.pyplot as plt #python在指定的时间段生成周期性波动的数据: #周期性 lon ...

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

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

  7. python 生成随机数_python 生成随机数模块random 常用方法总结

    random.random() 用来随机生成一个0到1之间的浮点数,包括零. In [1]: import random In [2]: random.random() Out[2]: 0.15790 ...

  8. python取随机小数_python生成2位小数点的随机数

    原博文 2017-10-23 21:01 − #coding=utf-8 import random #生成随机数,浮点类型 a = random.uniform(10, 20) #控制随机数的精度r ...

  9. python生成正态分布随机数_python 生成呈正态分布序列

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明.股市波动是不可预知的,但是股票的涨幅概率却呈现了正态分布的特点, 那么python如何生成呈正态分布 ...

最新文章

  1. java读取系统中指定的文件_java读取jar中指定的文件
  2. 51nod 1049 最大子段和
  3. CV_MAT_ELEM——获取矩阵元素和初始化矩阵
  4. Maven学习总结(26)——maven update时,报:Preference node org.eclipse.wst.validation...
  5. ES6 Reflect使用笔记
  6. AudioToolbox音效播放
  7. C#事件-经典小例子
  8. 与动易模板制作相关的几篇教程链接
  9. Lena图像分解成小块与从小块合成
  10. 领导人怎样带领好团队
  11. [含lw+源码等]S2SH+mysql的报刊订阅系统[包运行成功]Java毕业设计计算机毕设
  12. Sigmoid Belief Net
  13. plot指定线段形状和颜色_形状和颜色背后的心理学
  14. YII2 高级版本 发送163邮件
  15. MBA包括哪些课程?看完这个系列的书籍你就知道了
  16. YOLOE,2022年新版YOLO解读
  17. 解决vue项目在ie、360兼容模式下空白页面问题
  18. PTA python 币值转换 ,逆序数
  19. 算法_二叉树_二叉树的最大深度
  20. 【消息中心】架构准备

热门文章

  1. regexp_like 方法
  2. 1小时搞懂设计模式之委派模式
  3. 基于JAVA+SpringMVC+Mybatis+MYSQL的病例管理系统
  4. 基于JAVA+Servlet+JSP+MYSQL的酒店管理系统
  5. Form中获取数据源及扩展方法中获取变量
  6. 位图bitmap应用
  7. BZOJ 4031: [HEOI2015]小Z的房间 Matrix-Tree定理
  8. SQL Server - FileTable
  9. 网上图书商城项目学习笔记-008修改密码功能
  10. pku 1463 Strategic game 树形DP