python中的随机函数小结

时间:2022-09-20 23:17:46

本系列不会对python语法,理论作详细说明;所以不是一个学习教材;而这里只是我一个学习python的某些专题的总结。

1. random()函数 

描述:random() 方法返回随机生成的一个实数,它在[0,1)范围内。    

语法:

?
1
2
import random
random.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 random
random.randrange ([start,] stop [,step])

参数:

  1. start -- 指定范围内的开始值,包含在范围内
  2. stop -- 指定范围内的结束值,不包含在范围内。
  3. 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 random
random.randint(x,y)

参数:

  1. x -- 指定范围内的开始值,包含在范围内
  2. 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 random
random.uniform (x,y)

参数:

  1.  x -- 指定范围内的开始值,包含在范围内
  2. 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 random
random.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 random
random.sample(x,n)

参数:

  1. x -- list,tuple,strings的一种
  2. 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 random
random.shuffle(x)

参数:

  1.  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']

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/lottu/p/5600371.html