本文要跟大家分享的是Python隨機數random模組的幾個常用的方法,非常的簡單,小夥伴們喜歡的話,後續繼續深入探討
">
random 模組是Python自帶的模組,除了產生最簡單的隨機數字以外,還有很多功能。 0~1之間的隨機浮點數,範圍[0,10
>>> import random
>>> random.random()0.5038461831828231
random.uniform(a,b)
傳回a,b之間的隨機浮點數,範圍[a,b]或[a,b),取決於四捨五入,a不一定要比b小。
整數,範圍[a,b],注意:傳入參數必須是整數,a一定要比b小
>>> random.randint(50,100)
54
>>> random.randint(100,50)
Traceback (most recent call last):
File "
random.randint(100,50)
File "C:\Python27\lib\random.py", line 242, in randint
return
self.rand
range #(a, b+1) File "C:\Python27\lib\random.py", line 218, in randrange raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width
)
ValueError: empty range for randrange() (100,51, -49)
>>> random.randint( 50.5,100.6) Traceback (most recent call last): File "
File "C:\Python27\lib\random.py", line 242, in randint
return self.randrange(a, b+1) File "C:\Python27\lib\random. py", line 187, in randrange raise ValueError, "non-
integer
arg 1 for randrange()"
ValueError: non-integer arg 1 for randrange()
random.randrang([start], stop[, step])
傳回有個區間內的整數,可以設定step。只能傳入整數,random.randrange(10, 100, 2),結果相當於從[10, 12, 14, 16, … 96, 98]序列中取得隨機數。
>>> random.randrange(100)
58>>> random.randrange(10,100,2)54
list
, tuple,字串
都屬於sequence。這裡的sequence 需要是有序類型。 random.randrange(10,100,2)在結果上與random.choice(range(10,100,2) 等價。
>>> random.choice(("stone","scissors", "paper"))
>>> random.choice(["stone","scissors","paper"])
'scissors'>> ;> random.choice("Random")'m'random.shuffle
(x[,random])
用於將清單中的元素打亂,俗稱為洗牌。 ,"6","7","8","9","10","J","Q","K"]
>>> random.shuffle(poker)
>>> poker
['4', '10', '8', '3', 'J', '6', '2', '7', '9', 'Q ', '5', 'K', 'A']
從指定序列中隨機取得k個元素作為一個片段傳回,sample函數不會修改原有序列。
>>> poker = ["A","2","3","4","5","6","7","8","9" ,"10","J","Q","K"]
>>> random.sample(poker,5)
['4', '3', '10', '2', 'Q']
上述幾個方式是Python常用的一些方法,但關於隨機數還有很多的故事。下回分解~
以上是Python隨機數random模組詳解及實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!