目录:
生成 [0, 1) 之间的随机浮点数。
import random
print(random.random()) # 例如: 0.37444887175646646
生成 [a, b] 范围内的随机浮点数。
import random
print(random.uniform(1, 10)) # 例如: 7.894321456789
print(random.uniform(-5, 5)) # 例如: -2.34567891234
生成 [a, b] 范围内的随机整数。
import random
print(random.randint(1, 10)) # 例如: 7
print(random.randint(1, 100)) # 例如: 42
生成 range(start, stop, step) 范围内随机整数。
print(random.randrange(0, 101, 2)) # 随机偶数: 76
print(random.randrange(1, 101, 2)) # 随机奇数: 17
print(random.randrange(10)) # 0-9的随机整数: 3
random.choice(seq) 从非空列表中随机选择一个元素,如果列表为空,则报错 IndexError。
import random
fruits = ['apple', 'banana', 'cherry', 'date']
print(random.choice(fruits)) # 例如: banana
sports = []
print(random.choice(sports)) # 报错:raise IndexError
random.sample(population, k),其中 k 不能大于列表的长度。
import random
fruits = ['apple', 'banana', 'cherry', 'date']
print(random.sample(fruits, 2)) # 例如: ['cherry', 'apple']
print(random.sample(fruits, 10)) # 报错,10 大于列表总长度
random.shuffle(x) 会直接修改原列表。
import random
# 打乱序列顺序
deck = list(range(1, 11))
print("原始:", deck) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(deck)
print("打乱后:", deck) # 例如: [5, 9, 4, 6, 1, 3, 2, 8, 7, 10]
↶ 返回首页 ↶