產生(0,1)範圍的隨機浮點數
>>> i=0>>> while i<10:
(random.random())
i+=1
0.9848013389436461
0.4012610801121991
0.9401837669813049
0.36164185591353215
0.7291907908539083
0.7861886854506668
0.36611102654772787
0.37398351354553305
0.12664074395881753
0.12236860697016771
產生(m,n)範圍的隨機浮點數
>>> i=0>>> while i<10:
print(random.uniform(1,3))
i+=1
1.6814043787561306
1.0907622843587292
1.009237282651322
2.2605331784482594
2.1378180187272346
1.668827901441295
2.8266941473808895
1.5744320484197392
1.432510006768112
2.8973319467167453
產生[m, n]範圍的隨機整數
>>> i=0>>> while i<10:
print(random.randint(1,5),end=', '
) i+=1
3, 2, 4, 5, 5, 4, 5, 1, 2, 4,
產生[m, n)範圍內的隨機整數
>>> i=0>>> while i<10:
print(random.randrange(1,5),end=', '
) i+=1
3, 1, 3, 3, 2, 4, 3, 1, 4, 1,
傳入乙個可迭代物件,在該物件中隨機選擇乙個元素
>>> i=0>>> while i<10:
print(random.choice([1,2,3,4,5]),end=', '
) i+=1
2, 4, 4, 2, 4, 2, 4, 3, 5, 1,
傳入乙個可迭代物件,在該物件中隨機選擇n個元素
>>> i=0>>> while i<10:
a, b = random.sample([1,2,3,4,5],2)
print((a,b),end=', '
) i+=1(2, 3), (2, 4), (5, 2), (5, 3), (5, 4), (3, 2), (2, 1), (4, 5), (4, 1), (1, 4),
傳入乙個有序可迭代物件,可打亂其元素順序
>>> li=[1,2,3,4,5,6,7]>>> i=0
>>> while i<10:
random.shuffle(li)
(li)
i+=1[6, 2, 5, 4, 1, 3, 7]
[7, 6, 5, 3, 2, 1, 4]
[7, 2, 6, 1, 4, 3, 5]
[6, 5, 4, 3, 7, 1, 2]
[4, 2, 1, 5, 3, 7, 6]
[3, 2, 4, 7, 5, 1, 6]
[2, 3, 6, 4, 7, 1, 5]
[1, 5, 7, 6, 2, 3, 4]
[3, 2, 7, 6, 5, 4, 1]
[5, 7, 6, 1, 3, 4, 2]
python內建模組之random模組
import random print random.random 隨機 0 1 浮點數 print random.uniform 1,10 隨機指定範圍的浮點數 print random.randint 1,3 隨機整數1 3,包括3 print random.randrange 1,3 1 3隨...
Python之random模組筆記
一 匯入模組 import random二 random模組功能介紹 1 random.random 用於生成0 1的隨機浮點數,0 n 1.0 import random a random.random print a 2 random.uniform a,b 用於生成指定範圍內的隨機浮點數,其中...
python入門之random模組
usr bin env python encoding utf 8 import random print random.random 生成乙個在0到1之間的隨機浮點數 print random.randint 1,9 生成乙個在1到9之間的隨機整數,包含1和9 print random.randr...