Python中random的詳細解釋。
首先我們要知道,random模塊中我們常用的有,randint,random, choice, choices, uniform, shuffle, randrange.
這些其實我們都可以用help方法來找到用法,在互動界面用help(方法)就會告訴,例如:
import random
>>> help(random.randint)
Help on method randint in module random:
randint(a, b) method of random.Random instance
Return random integer in range [a, b], including both end points.
上面就是輸出的內容。
一下我們就介紹一下這幾個的用法。
randint:
randint(a,b)在a到b中隨機處一個整數,概率相等,包括端點
random:
random()在【0,1)中隨機出一個小數
choice:
choice(一個串列),然后從串列中隨機選出一個數。
例如 random.choice([1,2,3])運行后會隨機出現1,2,3
choices:
choices(一個串列,概率,xxx,k=次數) 這里就比較復雜,當這樣呼叫,他會以概率k次從串列中選擇元素:
eg:choices(【1,2,3】,【0.1,0.2,0.7】,k=5)則會以1對應0.1,2對應0.2,3對應0.7 的概率出現五個數字
注:這里choices的第三個引數我也沒搞懂,所以最后要用k=5,直接用5會報錯 k默認值為1
uniform:
uniform(a.b)會在a,b間以正態分布的概率來出數
shuffle:
shuffle(一個串列),這里就如這個英文單詞,洗牌。把這個串列的順序打亂
eg:shuffle(【1,2,3】)運行后會可能會打亂1,2,3的順序
randrange:
randrange(開始,結束=None,步數=1),這中間有兩個是默認的,可以修改,如果沒有結束的話 就從0到開始中選擇數字,
如果有結束 ,則從開始到結束,其中步數就是步長比如 如果你從1凱開始,步數為2 那么他會從 3,5,7等數字選
eg:randrange(1,7,2)運行后會隨機出現3,5,7
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/38416.html
標籤:其他
