1 # random各种使用方法 2 import random 3 4 # 随机生成[0.1)的浮点数 5 print("random():", random.random()) 6 7 # 随机生成1000-9999之间的整数 8 print("randint(1000, 9999):", random.randint(1000, 9999)) 9 10 # 随机生成0-20之间的偶数 11 print("randrange(0, 21, 2):", random.randrange(0, 21, 2)) 12 13 # 随机生成0-20之间的浮点数 14 print("uniform(0, 20):", random.uniform(0, 20)) 15 16 # 从序列中随机选择一个元素 17 list_string = [‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘] 18 print("choice(list):", random.choice(list_string)) 19 print("choice(string):", random.choice(‘abcd‘)) 20 21 # 对列表元素随机排序 22 list_number = [1, 2, 3, 4, 5] 23 random.shuffle(list_number) 24 print("shuffle(list):", list_number) 25 26 # 从指定序列中随机获取指定长度的片断 27 print("sample(sequence):", random.sample(‘abcdefg‘, 2)) 28 29 30 31 运行结果: 32 33 random(): 0.6708362810735843 34 randint(1000, 9999): 5228 35 randrange(0, 21, 2): 6 36 uniform(0, 20): 12.767906137387294 37 choice(list): a 38 choice(string): d 39 shuffle(list): [1, 3, 5, 2, 4] 40 sample(sequence): [‘f‘, ‘g‘]
原文:https://www.cnblogs.com/up-day/p/8780347.html