python常用模块——random模块

参考博客:http://www.360doc.com/content/14/0430/11/16044571_373443266.shtml

今天突然想起python该怎么生成随机数?查了一下,贴出实验结果

首先要导入import这个模块

random模块中常用的函数
random() 随机生成一个浮点数,范围在0到1之间
uniform() 随机生成指定范围之内的浮点数
randint() 随机生成指定范围之内的整数
randrange() 随机生成指定范围之内的整数,可以指定步长
choise() 随机从一个序列中选择一个元素
shuffle() 将列表的顺序打乱
sample() 随机获取序列中指定的数量的元素

 

 

 

 

 

 

 

 

1.random.random():随机生成一个浮点数,范围在0<=x<=1.0

>>> random.random()
0.7802959818148015
>>> random.random()
0.328008839087651
>>> random.random()
0.5568708122526114
>>> random.random()
0.23048925282509325

 

2.random.uniform():随机生成指定范围内的随机浮点数。

>>> random.uniform(18,15)  a >b a<b a=b 均可
16.01770569291661
>>> random.uniform(18,15)
17.027730377035027
>>> random.uniform(10,15)
14.682052726572774
>>> random.uniform(10,15)
12.997092389884806

 

3.random.randint():随机选取一个范围内的整数

>>> random.randint(12,14)
12
>>> random.randint(12,16)
14
>>> random.randint(12,16)
16

 

4.random.randrange():和randranint()类似,返回范围内的一个整数,randrange()可以指定数值的步长。

>>> random.randrange(10,100)
97
>>> random.randrange(10,100)  #步长默认1
89
>>> random.randrange(10,100,2)
66
>>> random.randrange(10,100,2)
52
>>> random.randrange(10,1,2)    #第一个数必须小于第二个数
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/python3.6/lib/python3.6/random.py", line 212, in randrange
    raise ValueError("empty range for randrange()")
ValueError: empty range for randrange()

 

 

5.random.chiose():随机选取序列中的一个元素

>>> random.choice(('kebi','maoxina','xinye'))
'xinye'
>>> 
>>> random.choice(('kebi','maoxina','xinye'))
'kebi'
>>> random.choice([1,2,3,4])
2
>>> random.choice([1,2,3,4])
2
>>> random.choice("老男孩IT教育")
''
>>> random.choice("老男孩IT教育")
''

 

6.random.shuffle():将列表中的一个元素打乱

>>> name = ['kebi','喜欢','']
>>> random.shuffle(name)
>>> name
['喜欢', '', 'kebi']
>>> random.shuffle(name)
>>> name
['kebi', '喜欢', '']
>>> random.shuffle(name)
>>> name
['喜欢', '', 'kebi']

 

7.random.sample():随机获取序列中指定数量的元素

>>> ss = (1,2,3,4)
>>> sst = 'woshishui'
>>> random.sample(ss,2)
[2, 4]
>>> random.sample(ss,2)
[2, 1]
>>> random.sample(sst,1)
['h']
>>> random.sample(sst,4)  #不是切片,没有顺序
['o', 'u', 'i', 'w']

>>> random.sample(name)  #必须要指定数量
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sample() missing 1 required positional argument: 'k'
>>> random.sample(name,2)
['', '喜欢']
>>> random.sample(name,1)
['']

 

posted @ 2017-10-26 11:34  明王不动心  阅读(426)  评论(0编辑  收藏  举报