Python 随机数模块random最常用的8个方法

简介: Python 随机数模块random最常用的8个方法


常用函数列表

>>> import random
>>> [i for i in dir(random) if i[0]>='a']
['betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss',
 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate',
 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle',
 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']



内置英语帮助

>>> import random
>>> [eval(f'print("No.",i+1,":"),help(random.{j})') for i,j in enumerate([i for i in dir(random) if i[0]>='a'])]



运行结果如下,一共22个函数:

No. 1 :
Help on method betavariate in module random:
betavariate(alpha, beta) method of random.Random instance
    Beta distribution.
    Conditions on the parameters are alpha > 0 and beta > 0.
    Returned values range between 0 and 1.
No. 2 :
Help on method choice in module random:
choice(seq) method of random.Random instance
    Choose a random element from a non-empty sequence.
No. 3 :
Help on method choices in module random:
choices(population, weights=None, *, cum_weights=None, k=1) method of random.Random instance
    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.
No. 4 :
Help on method expovariate in module random:
expovariate(lambd) method of random.Random instance
    Exponential distribution.
    lambd is 1.0 divided by the desired mean.  It should be
    nonzero.  (The parameter would be called "lambda", but that is
    a reserved word in Python.)  Returned values range from 0 to
    positive infinity if lambd is positive, and from negative
    infinity to 0 if lambd is negative.
No. 5 :
Help on method gammavariate in module random:
gammavariate(alpha, beta) method of random.Random instance
    Gamma distribution.  Not the gamma function!
    Conditions on the parameters are alpha > 0 and beta > 0.
    The probability distribution function is:
                x ** (alpha - 1) * math.exp(-x / beta)
      pdf(x) =  --------------------------------------
                  math.gamma(alpha) * beta ** alpha
No. 6 :
Help on method gauss in module random:
gauss(mu, sigma) method of random.Random instance
    Gaussian distribution.
    mu is the mean, and sigma is the standard deviation.  This is
    slightly faster than the normalvariate() function.
    Not thread-safe without a lock around calls.
No. 7 :
Help on built-in function getrandbits:
getrandbits(k, /) method of random.Random instance
    getrandbits(k) -> x.  Generates an int with k random bits.
No. 8 :
Help on method getstate in module random:
getstate() method of random.Random instance
    Return internal state; can be passed to setstate() later.
No. 9 :
Help on method lognormvariate in module random:
lognormvariate(mu, sigma) method of random.Random instance
    Log normal distribution.
    If you take the natural logarithm of this distribution, you'll get a
    normal distribution with mean mu and standard deviation sigma.
    mu can have any value, and sigma must be greater than zero.
No. 10 :
Help on method normalvariate in module random:
normalvariate(mu, sigma) method of random.Random instance
    Normal distribution.
    mu is the mean, and sigma is the standard deviation.
No. 11 :
Help on method paretovariate in module random:
paretovariate(alpha) method of random.Random instance
    Pareto distribution.  alpha is the shape parameter.
No. 12 :
Help on method randint in module random:
randint(a, b) method of random.Random instance
    Return random integer in range [a, b], including both end points.
No. 13 :
Help on built-in function random:
random() method of random.Random instance
    random() -> x in the interval [0, 1).
No. 14 :
Help on method randrange in module random:
randrange(start, stop=None, step=1, _int=<class 'int'>) method of random.Random instance
    Choose a random item from range(start, stop[, step]).
    This fixes the problem with randint() which includes the
    endpoint; in Python this is usually not what you want.
No. 15 :
Help on method sample in module random:
sample(population, k) method of random.Random instance
    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)
No. 16 :
Help on method seed in module random:
seed(a=None, version=2) method of random.Random instance
    Initialize internal state from hashable object.
    None or no argument seeds from current time or from an operating
    system specific randomness source if available.
    If *a* is an int, all bits are used.
    For version 2 (the default), all of the bits are used if *a* is a str,
    bytes, or bytearray.  For version 1 (provided for reproducing random
    sequences from older versions of Python), the algorithm for str and
    bytes generates a narrower range of seeds.
No. 17 :
Help on method setstate in module random:
setstate(state) method of random.Random instance
    Restore internal state from object returned by getstate().
No. 18 :
Help on method shuffle in module random:
shuffle(x, random=None) method of random.Random instance
    Shuffle list x in place, and return None.
    Optional argument random is a 0-argument function returning a
    random float in [0.0, 1.0); if it is the default None, the
    standard random.random will be used.
No. 19 :
Help on method triangular in module random:
triangular(low=0.0, high=1.0, mode=None) method of random.Random instance
    Triangular distribution.
    Continuous distribution bounded by given lower and upper limits,
    and having a given mode value in-between.
    http://en.wikipedia.org/wiki/Triangular_distribution
No. 20 :
Help on method uniform in module random:
uniform(a, b) method of random.Random instance
    Get a random number in the range [a, b) or [a, b] depending on rounding.
No. 21 :
Help on method vonmisesvariate in module random:
vonmisesvariate(mu, kappa) method of random.Random instance
    Circular data distribution.
    mu is the mean angle, expressed in radians between 0 and 2*pi, and
    kappa is the concentration parameter, which must be greater than or
    equal to zero.  If kappa is equal to zero, this distribution reduces
    to a uniform random angle over the range 0 to 2*pi.
No. 22 :
Help on method weibullvariate in module random:
weibullvariate(alpha, beta) method of random.Random instance
    Weibull distribution.
    alpha is the scale parameter and beta is the shape parameter.
[(None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None), (None, None)]




最常用随机函数


选择其中最常用的8个函数进行用法测试:


1. random() -> x in the interval [0, 1).

# 生成随机纯小数
>>> random.random()
0.4203557245596913
>>> random.random()
0.07523540148971974
>>> random.random()
0.18567496593579502
>>> 




2. randint(a, b) method of random.Random instance

    Return random integer in range [a, b], including both end points.

# 生成开区间内的随机整数,包括区间两头的整数
>>> random.randint(1,6)
3
>>> random.randint(1,6)
2
>>> random.randint(1,6)
6
>>> 

bfc4b783c68c49a8b3da5c2733988b37.png


3. uniform(a, b) method of random.Random instance

    Get a random number in the range [a, b) or [a, b] depending on rounding.

# 生成前开后闭区内的随机浮点数
>>> random.uniform(1,8)
7.370822144312884
>>> random.uniform(1,8)
4.466816494748985
>>> random.uniform(1,8)
1.8154762190957459
>>> 



4. randrange(start, stop=None, step=1, _int=<class 'int'>)

# 指定范围内的随机整数,有步长参数比如step=2时只生成奇数或偶数
>>> random.randrange(3,8)
5
>>> random.randrange(3,8)
3
>>> random.randrange(3,18,2)
9
>>> random.randrange(3,18,2)
13
>>> 



5. choice(seq) method of random.Random instance

    Choose a random element from a non-empty sequence.

# 随机取出序列中的一个元素
>>> random.choice('abcdef')
'd'
>>> random.choice('abcdef')
'f'
>>> random.choice('abcdef')
'b'
>>> random.choice([1,22,333,4444])
333
>>> random.choice([1,22,333,4444])
1
>>> random.choice([1,22,333,4444])
22
>>> 



6. shuffle(x, random=None) method of random.Random instance

    Shuffle list x in place, and return None.

# 给列表随机排序,俗称“洗牌”函数
>>> random.shuffle([1,2,3,4,5,6])
>>> a = [1,2,3,4,5,6]
>>> random.shuffle(a)
>>> a
[4, 6, 5, 2, 3, 1]
>>> random.shuffle(a)
>>> a
[3, 6, 1, 5, 4, 2]
>>> b = 'abcdef'
>>> b = list(b)
>>> random.shuffle(b)
>>> b=''.join(b)
>>> b
'cdaefb'
>>> 



7. sample(population, k) method of random.Random instance

    Chooses k unique random elements from a population sequence or set.

# 在range()指定范围内,返回指定个数的随机数样本列表
>>> random.sample(range(10000), 10)
[1817, 5551, 3549, 8889, 750, 265, 5890, 7658, 4068, 1249]
>>> random.sample(range(100,1000), 12)
[786, 280, 897, 970, 767, 554, 874, 229, 289, 318, 112, 275]
>>> 
>>> # 也可以和shuffle()用法一样,不同的是shuffle在原列表上改动
>>> random.sample([1,2,3,4,5,6], 6)
[6, 1, 3, 2, 5, 4]
>>> random.sample([1,2,3,4,5,6], 6)
[5, 4, 2, 6, 1, 3]
>>> 




8. seed(a=None, version=2) method of random.Random instance

    Initialize internal state from hashable object.

# 初始化随机数种子
>>> def randnum():
    # 不设置种子,样本不固定
  return random.randint(1,6)
>>> randnum()
1
>>> randnum()
6
>>> randnum()
4
>>> def randnumseed(seed=1):
    # 设置随机数种子后,种子对应的样本固定
  random.seed(seed)
  return random.randint(1,6)
>>> randnumseed()
2
>>> randnumseed()
2
>>> randnumseed()
2
>>> randnumseed(2)
1
>>> randnumseed(2)
1
>>> randnumseed(2)
1
>>> randnumseed(12345)
4
>>> randnumseed(12345)
4
>>> 


其它函数用于概率论中的伽玛分布等,理论比较高深,略。


目录
相关文章
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
1417 7
|
监控 安全 程序员
Python日志模块配置:从print到logging的优雅升级指南
从 `print` 到 `logging` 是 Python 开发的必经之路。`print` 调试简单却难维护,日志混乱、无法分级、缺乏上下文;而 `logging` 支持级别控制、多输出、结构化记录,助力项目可维护性升级。本文详解痛点、优势、迁移方案与最佳实践,助你构建专业日志系统,让程序“有记忆”。
1168 0
|
人工智能 数据安全/隐私保护 异构计算
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
1976 8
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
|
JSON 算法 API
Python中的json模块:从基础到进阶的实用指南
本文深入解析Python内置json模块的使用,涵盖序列化与反序列化核心函数、参数配置、中文处理、自定义对象转换及异常处理,并介绍性能优化与第三方库扩展,助你高效实现JSON数据交互。(238字)
972 4
|
Java 调度 数据库
Python threading模块:多线程编程的实战指南
本文深入讲解Python多线程编程,涵盖threading模块的核心用法:线程创建、生命周期、同步机制(锁、信号量、条件变量)、线程通信(队列)、守护线程与线程池应用。结合实战案例,如多线程下载器,帮助开发者提升程序并发性能,适用于I/O密集型任务处理。
1122 0
|
XML JSON 数据处理
超越JSON:Python结构化数据处理模块全解析
本文深入解析Python中12个核心数据处理模块,涵盖csv、pandas、pickle、shelve、struct、configparser、xml、numpy、array、sqlite3和msgpack,覆盖表格处理、序列化、配置管理、科学计算等六大场景,结合真实案例与决策树,助你高效应对各类数据挑战。(238字)
1562 0
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
1105 0
|
算法 安全 量子技术
【Python】蒙特卡洛模拟 | PRNG 伪随机数发生器 | 马特赛特旋转算法 | LCG 线性同余算法 | Python Random 模块
【Python】蒙特卡洛模拟 | PRNG 伪随机数发生器 | 马特赛特旋转算法 | LCG 线性同余算法 | Python Random 模块
1569 0
|
Python
python之math,random模块的使用方法
python之math,random模块的使用方法
398 0
|
数据挖掘 测试技术 数据安全/隐私保护
软件测试|Python random模块,超乎想象的强大
软件测试|Python random模块,超乎想象的强大

推荐镜像

更多