- 随机生成[0.1)的浮点数
random()
print("random():", random.random())
- 随机生成1000-9999之间的整数
randint(1000, 9999)
print("randint(1000, 9999):", random.randint(1000, 9999))
- 随机生成0-20之间的偶数
randrange(0, 21, 2),返回整型数值
print("randrange(0, 21, 2):", random.randrange(0, 21, 2))
- 随机生成0-20之间的浮点数
uniform(0, 20),返回浮点型数值
print("uniform(0, 20):", random.uniform(0, 20))
- 从序列中随机选择一个元素
choice(list),参数为list
list_string = ['a', 'b', 'c', 'd', 'e']
print("choice(list):", random.choice(list_string))
print("choice(string):", random.choice('abcd'))
- 对列表元素随机排序
shuffle(list),参数为list
list_number = [1, 2, 3, 4, 5]
random.shuffle(list_number)
print("shuffle(list):", list_number)
- 从指定序列中随机获取指定长度的片断
sample(sequence),必须传入两个参数
print("sample(sequence):", random.sample('abcdefg', 2))
输出结果:
random(): 0.3246915361854795
randint(1000, 9999): 7801
randrange(0, 21, 2): 16
uniform(0, 20): 3.0944129126831754
choice(list): c
choice(string): c
shuffle(list): [4, 3, 2, 1, 5]
sample(sequence): ['d', 'c']