python - Random常用方法记录

时间:2023-03-09 06:31:07
python - Random常用方法记录
import random

# range [a,b)   不包含b

# 获取随机整数
# randrange [a,b) 不包含b
a = random.randrange(0, 101, 5) # Even integer from 0 to 100 inclusive 5 - step
print(a) #
# randint[a, b] 包含b
b = random.randint(0, 1)
print(b) # # 获取0.0 - 1.0之间的随机浮点数
c = random.random() # Random float: 0.0 <= x < 1.0
print(c) # 0.15039929566062382 # 根据设定的浮点数范围,获取随机浮点数
d = random.uniform(2.5, 10.0) # # Random float: 2.5 <= x < 10.0
print(d) # 3.3330140631461425 # 序列用函数
# 从非空序列 seq 返回一个随机元素
li = ['aa', 'bb', 'cc', 'dd', 'ee']
b = random.choice(li)
print(b) # aa # 将序列 x 随机打乱位置 改变的是列表
li = "my name is Melody".split()
print(li) # ['my', 'name', 'is', 'Melody']
random.shuffle(li)
print(li) # ['Melody', 'is', 'my', 'name'] # random.sample(population, k)
# 从指定的序列中,随机的截取指定长度的片断,不作原地修改
li = [2, 3, 4, 6, 7, 9, 0]
b = random.sample(li, 3)
print(b) # [4, 6, 2]
print(li) # 原列表未改变 [2, 3, 4, 6, 7, 9, 0]