文章目录
random 模块简介
用于生成随机数,可按照一定的规则生成指定范围内的随机数,如后续示例所示
示例一:random.random()
import random
print(random.random())
print(random.random())
print(random.random())
print(random.random())
"""
0.7549817872782207
0.8463429995114858
0.5849971147917522
0.8639473485804318
"""
默认是随机输出1以内的小数
示例二:random.randint()----指定范围内随机整数
import random
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
print(random.randint(1,10))
"""
9
9
7
7
1
5
3
4
4
7
"""
示例三:random.choice()–从一个序列中随机选择一个
import random
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice("Elon Mask"))
print(random.choice(["Elom Mask","Tesla",["Space X","Rocket"]]))
"""
E
k
s
E
M
s
n
Tesla
"""
random.shuffle()
将顺序打乱,再随机排序
Help on method shuffle in module random:
shuffle(x, random=None) method of random.Random instance
Shuffle list x in place, and return None.
Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.
None
random.sample()–随机选取指定数量的元素
import random
print(random.sample(["Elom Mask","Tesla",["Space X","Rocket"]],2))
print(random.sample(["Elom Mask","Tesla",["Space X","Rocket"]],2))
"""
['Tesla', ['Space X', 'Rocket']]
['Tesla', 'Elom Mask']
"""
random.randrange()–指定范围内随机,不包含最右侧
import random
print(random.randrange(1,8))
"""
5
"""