- 工信部备案号 滇ICP备05000110号-1
- 滇公网安备53011102001527号
- 增值电信业务经营许可证 B1.B2-20181647、滇B1.B2-20190004
- 云南互联网协会理事单位
- 安全联盟认证网站身份V标记
- 域名注册服务机构许可:滇D3-20230001
- 代理域名注册服务机构:新网数码
- CN域名投诉举报处理平台:电话:010-58813000、邮箱:service@cnnic.cn
1. random()函数
描述:random() 方法返回随机生成的一个实数,它在[0,1)范围内。
语法:
1 2 | import randomrandom.random(); |
注意:random()是不能直接访问的,需要导入 random 模块,然后通过 random 静态对象调用该方法。
实例演示:
1 2 3 4 5 | >>> import random>>> print random.random();0.803119901575>>> print random.random();0.451592468747 |
2. randrange()函数
描述: randrange() 方法返回指定递增基数集合中的一个随机数,基数缺省值为1。返回一个整数
语法
1 2 | import randomrandom.randrange ([start,] stop [,step]) |
参数:
start -- 指定范围内的开始值,包含在范围内
stop -- 指定范围内的结束值,不包含在范围内。
step -- 指定递增基数
实例演示
1 2 3 4 5 6 7 8 | >>> print random.randrange(10);4>>> print random.randrange(5,10);7>>> print random.randrange(5,10,3);5>>> print random.randrange(5,10,3);8 |
3.randint()函数
描述:randint()方法将随机生成一个整数,它在[x,y]范围内 ;有点等价于randrange(x,y+1).
语法
1 2 | import randomrandom.randint(x,y) |
参数:
x -- 指定范围内的开始值,包含在范围内
y -- 指定范围内的结束值,包含在范围内。
实例演示
1 2 3 4 | >>> print random.randrange(5,10);9>>> print random.randint(5,10);6 |
4. uniform()函数
描述:uniform() 方法将随机生成下一个实数,它在[x,y]范围内。返回一个浮点数
语法:
1 2 | import randomrandom.uniform (x,y) |
参数:
x -- 指定范围内的开始值,包含在范围内
y -- 指定范围内的结束值,包含在范围内。
实例演示
1 2 3 4 | >>> print random.uniform(5,10);9.13282585434>>> print random.uniform(9,10);9.95958315062 |
5. choice()函数
描述:choice() 方法返回一个列表,元组或字符串的随机项。
语法
1 2 | import randomrandom.choice(x) |
参数:
x -- list,tuple,strings的一种
实例演示
1 2 3 4 5 6 | >>> print random.choice(('a','be',5,'e'))5>>> print random.choice([10,2,6,5,85,'af'])85>>> print random.choice('i love python')v |
6. sample()函数
描述:sample()方法返回随机从列表,元组或字符串其中部分随机项 ;返回类型为元组类型
语法
1 2 | import randomrandom.sample(x,n) |
参数:
x -- list,tuple,strings的一种
n -- 返回n个随机项
实例演示
1 2 3 4 5 6 | >>> print random.sample('i love python',3)[' ', 'e', 'i']>>> print random.sample([10,20,50,23,'ab'],3)[50, 'ab', 23]>>> print random.sample((10,20,50,23,'ab'),3)[50, 20, 'ab'] |
7. shuffle()函数
描述:shuffle() 方法将序列的所有元素随机排序。类似于洗牌
语法 :
1 2 | import randomrandom.shuffle(x) |
参数:
x -- list,tuple的一种;python2.x只支持list类型
实例演示
1 2 3 4 | >>> list=['a','b','c','d','e'];>>> random.shuffle(list);>>> print list;['c', 'd', 'a', 'e', 'b'] |
拓展:将元祖反转;实现reverse函数的效果
1 2 3 4 | >>> list=['a','b','c','d','e'];>>> list1=list[::-1]>>> print list1['e', 'd', 'c', 'b', 'a'] |
售前咨询
售后咨询
备案咨询
二维码

TOP