接下來。裝逼開始....
random --- 生成隨機數
生成隨機小數import random
print(random.random())0.7195625930629974
Process finished with exit code 0import random
print(random.uniform(1, 2))1.4247584611406854
Process finished with exit code 0生成隨機整數import random
print(random.randint(1, 20))import random
print("10 ~ 20 之間的偶數:", random.randrange(10, 20, 2))
print("10 ~ 20 之間的其他數:", random.randrange(10, 20, 3))10 ~ 20 之間的偶數: 1410 ~ 20 之間的其他數: 16
Process finished with exit code 0import random
print(random.getrandbits(10))802
Process finished with exit code 0序列函數
import random
print(random.choice('123456'))print(random.choice([1, 2, 3, 4, 5, 6]))print(random.choice((1, 2, 3, 4, 5, 6)))print(random.choice([{1: 2}, {3: 4}, {5: 6}]))255{3: 4}
Process finished with exit code 0import random
print(random.choices('123456', k=3))print(random.choices([1, 2, 3, 4, 5, 6], k=2))print(random.choices((1, 2, 3, 4, 5, 6), k=3))print(random.choices([{1: 2}, {3: 4}, {5: 6}], k=1))['6', '3', '3'][4, 2][4, 2, 3][{1: 2}]
Process finished with exit code 0random.choices()中還有一個權重一說,例子如下
print(random.choices(['red', 'black', 'green'], [18, 18, 2], k=6))['red', 'black', 'black', 'red', 'red', 'black']
Process finished with exit code 0這裡需要注意的是,權重序列必須要和前面的序列長度一致的,不然就會拋出TypeError錯誤
import random
list_data = [1,2,3,4,5,6]random.shuffle(list_data)print(list_data)import random
list_data = [1,2,3,4,5,6]print(random.sample(list_data, 2))[5, 3]
Process finished with exit code 0通常使用最多的random.choice(),從序列中隨機拿一個參數;還有random.sample(),從序列中獲取兩條不重複的數據,用於接口中專門接收數組參數去傳值;如果接口有些名稱是要唯一性的,可以使用random.randint()、random.random()、random.uniform()生成隨機數後,然後再處理下使用...
以上總結或許能幫助到你,或許幫助不到你,但還是希望能幫助到你,如有疑問、歧義,直接私信留言會及時修正發布;非常期待你的點讚和分享喲,謝謝!
未完,待續…
一直都在努力,希望您也是!