Python random生成随机数示例

python生成随机数

随机整数:

>>> import random
>>> random.randint(0,99)
50

Python random生成随机数示例

随机选取0到100间的偶数:

>>> import random
>>> random.randrange(0, 101, 2)
2

Python random生成随机数示例

随机浮点数: 

>>> import random
>>> random.random()
0.011508602165174242 #范围0-1.0
>>> random.uniform(1, 10)
2.8229556607576147
>>>

Python random生成随机数示例

选择一个随机元素

>>> random.choice("abcde")
'b'
>>> random.choice("abcde")
'a'

Python random生成随机数示例

将一个列表中的元素打乱

Python random生成随机数示例

从指定序列中随机获取指定长度片段

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

Python random生成随机数示例

随机字符:

Python random生成随机数示例

多个字符中选取特定数量的字符:

Python random生成随机数示例

随机选取字符串:

Python random生成随机数示例

洗牌:

>>> import random
>>> items = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(items)
>>> items
[2, 1, 5, 7, 3, 4, 6]

Python random生成随机数示例

猜你喜欢

转载自www.linuxidc.com/Linux/2019-03/157639.htm