標籤:seq imp .sh python shuff nbsp print style 元素
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.670836281073584334 randint(1000, 9999): 522835 randrange(0, 21, 2): 636 uniform(0, 20): 12.76790613738729437 choice(list): a38 choice(string): d39 shuffle(list): [1, 3, 5, 2, 4]40 sample(sequence): [‘f‘, ‘g‘]
python之random函數