1. random()函数
描述: random() 方法返回随机生成的一个实数, 它在 [0,1) 范围内
语法:
- import random
- random.random();
注意: random()是不能直接访问的, 需要导入 random 模块, 然后通过 random 静态对象调用该方法
实例演示:
- >>> import random
- >>> print random.random();
- 0.803119901575
- >>> print random.random();
- 0.451592468747
2. randrange()函数
描述: randrange() 方法返回指定递增基数集合中的一个随机数, 基数缺省值为 1 返回一个整数
语法
- import random
- random.randrange ([start,] stop [,step])
参数:
start -- 指定范围内的开始值, 包含在范围内
stop -- 指定范围内的结束值, 不包含在范围内
step -- 指定递增基数
实例演示
- >>> 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).
语法
- import random
- random.randint(x,y)
参数:
x -- 指定范围内的开始值, 包含在范围内
y -- 指定范围内的结束值, 包含在范围内
实例演示
- >>> print random.randrange(5,10);
- 9
- >>> print random.randint(5,10);
- 6
4. uniform()函数
描述: uniform() 方法将随机生成下一个实数, 它在 [x,y] 范围内返回一个浮点数
语法:
- import random
- random.uniform (x,y)
参数:
x -- 指定范围内的开始值, 包含在范围内
y -- 指定范围内的结束值, 包含在范围内
实例演示
- >>> print random.uniform(5,10);
- 9.13282585434
- >>> print random.uniform(9,10);
- 9.95958315062
5. choice()函数
描述: choice() 方法返回一个列表, 元组或字符串的随机项
语法
- import random
- random.choice(x)
参数:
x -- list,tuple,strings 的一种
实例演示
- >>> 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()方法返回随机从列表, 元组或字符串其中部分随机项 ; 返回类型为元组类型
语法
- import random
- random.sample(x,n)
参数:
x -- list,tuple,strings 的一种
n -- 返回 n 个随机项
实例演示
- >>> 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() 方法将序列的所有元素随机排序类似于洗牌
语法 :
- import random
- random.shuffle(x)
参数:
x -- list,tuple 的一种; python2.x 只支持 list 类型
实例演示
- >>> list=['a','b','c','d','e'];
- >>> random.shuffle(list);
- >>> print list;
- ['c', 'd', 'a', 'e', 'b']
拓展: 将元祖反转; 实现 reverse 函数的效果
- >>> list=['a','b','c','d','e'];
- >>> list1=list[::-1]
- >>> print list1
- ['e', 'd', 'c', 'b', 'a']
来源: http://www.phperz.com/article/18/0213/363222.html