python标准库常用模块(二)-----------------------------random模块详解及相关演示代码

1.产生0到1之间的随机数:random()

>>> random.random()
0.27541534375371846
>>> random.random()
0.32671084821496754

2.产生特定区间的随机整数(头和尾都包括):randint(start,end)

>>> random.randint(1,10)
9
>>> random.randint(1,10)
1

3.产生特定区间的随机整数(包含头不包含尾):randrange(10)

>>> random.randrange(10)
4
>>> random.randrange(10)
0

范围是0到9

4.对特定的字符串,列表中的内容进行随机取一位:choice()

>>> random.choice('abcdefg')
'b'

>>> random.choice([1,2,3,4,5,6])
2

5.随机取字符串或列表中的若干内容:sample()

>>> random.sample('abcdefg',3)
['c', 'f', 'g']

>>> random.sample([1,2,3,4,5,6,7,8,9],3)
[6, 4, 2]

6.取给定区间的浮点数:uniform()

>>> random.uniform(1,10)
7.876086414991905

7.对给定的内容的顺序进行打乱:shuffle()

>>> a=[1,2,3,4,5,6,7,8,9]
>>> print(a)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> random.shuffle(a)
>>> print(a)
[9, 1, 4, 5, 7, 8, 3, 6, 2]

猜你喜欢

转载自blog.csdn.net/qq_41901915/article/details/82632523
今日推荐