python产生随机数的方法
来源:互联网 发布:tensorflow文档 编辑:程序博客网 时间:2024/06/05 21:53
1,在两个数之间产生一个随机数。
>>> random.uniform(1,5)
1.6035288788035151
>>>
2,产生整数
>>> random.randint(1,10)
3
>>>
3,在0,1之间产生数
>>> random.random()
0.6324144022270801
>>>
如果你对在Python生成随机数与random模块中最常用的几个函数的关系与不懂之处,下面的文章就是对Python生成随机数与random模块中最常用的几个函数的关系,希望你会有所收获,以下就是这篇文章的介绍。
random.random()用于生成
用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成随机数
n: a <
=
n <
=
b。如果 a <b, 则 b <
=
n <
=
a。
print
random.uniform(
10
,
20
)
print
random.uniform(
20
,
10
)
#----
#18.7356606526
#12.5798298022
random.randint
用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,Python生成随机数
print
random.randint(
12
,
20
)
#生成的随机数n: 12 <= n <= 20
print
random.randint(
20
,
20
)
#结果永远是20
#print random.randint(20, 10) #该语句是错误的。
下限必须小于上限。
random.randrange
从指定范围内,按指定基数递增的集合中 ,这篇文章就是对python生成随机数的应用程序的部分介绍。
随机整数:
>>> import random
>>> random.randint(0,99)
21
随机选取0到100间的偶数:
>>> import random
>>> random.randrange(0, 101, 2)
42
随机浮点数:
>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881
随机字符:
>>> import random
>>> random.choice('abcdefg&#%^*f')
'd'
多个字符中选取特定数量的字符:
>>> import random
random.sample('abcdefghij',3)
['a', 'd', 'b']
多个字符中选取特定数量的字符组成新字符串:
>>> import random
>>> import string
>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
eplace(" ","")
'fih'
随机选取字符串:
>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'
洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]
PS:最后再为大家提供两款相关在线工具供大家参考使用:
在线随机数字/字符串生成工具:
http://tools.jb51.net/aideddesign/suijishu
高强度随机字符密码生成器:
http://tools.jb51.net/password/CreateStrongPassword
- python产生随机数的方法
- python numpy 常用随机数的产生方法
- python随机数的产生
- 产生随机数的方法
- 产生随机数的方法:
- 产生随机数的方法
- 产生随机数的方法之一
- C++产生随机数的方法
- 产生随机数的正确方法
- java产生随机数的方法。
- java产生随机数的方法
- c#产生随机数的方法
- java产生随机数的方法
- Java 产生随机数的方法
- Java产生随机数的方法
- JAVA随机数的产生方法
- java产生随机数的方法
- matlab产生随机数的方法
- HDU-1208 Pascal's Travels 动态规划
- JSONP 教程
- appium无线连接移动端
- jsp页面乱码解决
- 判断一字符串是否为回文,是返回1,不是返回0,出错返回-1
- python产生随机数的方法
- spark安装配置
- Android进程和线程
- lazy懒加载(延迟加载)UITableView
- ***********MySQL索引详解
- HashSet实现原理及源码分析
- java基础之一异常
- 修改userdata 分区大小
- 逆向CrackMe-02写注册机