1. 程式人生 > >python之random函數

python之random函數

浮點數 方法 orm sequence 函數 number 偶數 print string

 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]

python之random函數