python中random函数的使用方法 详解
# random各种使用方法import random# 随机生成[0.1)的浮点数print("random():", random.random())# 随机生成1000-9999之间的整数print("randint(1000, 9999):", random.randint(1000, 9999))# 随机生成0-20之间的偶数print("randrange(0, 21, 2):", random.randrange(0, 21, 2))# 随机生成0-20之间的浮点数print("uniform(0, 20):", random.uniform(0, 20))# 从序列中随机选择一个元素list_string = ['a', 'b', 'c', 'd', 'e']print("choice(list):", random.choice(list_string))print("choice(string):", random.choice('abcd'))# 对列表元素随机排序list_number = [1, 2, 3, 4, 5]random.shuffle(list_number)print("shuffle(list):", list_number)# 从指定序列中随机获取指定长度的片断print("sample(sequence):", random.sample('abcdefg', 2))运行结果如下
random(): 0.6708362810735843randint(1000, 9999): 5228randrange(0, 21, 2): 6uniform(0, 20): 12.767906137387294choice(list): achoice(string): dshuffle(list): [1, 3, 5, 2, 4]sample(sequence): ['f', 'g']

浙公网安备 33010602011771号