Python之random(隨機數必知)

random.random 隨機0-1的浮點數

>>> import random  # 導入Random模塊
>>> random.random()
0.13789225599315458  # 運行結果

random.uniform 隨機1-3的浮點數

>>> import random  # 導入Random模塊
>>> random.uniform(1,3)
1.26721023109448  # 運行結果

random.randint 隨機1-3的整數

>>> import random  # 導入Random模塊
>>> random.randint(1,3)
2  # 運行結果

random.choice 隨機Python任意一個字母

>>> import random  # 導入Random模塊
>>> random.choice("Python")
't'  # 運行結果
>>> random.choice("Python")
'n'  # 運行結果
>>> random.choice("Python")
'o'  # 運行結果

random.sample 隨機list數組五個數字(sample函數不會修改list數組數字中的數字)

>>> import random  # 導入Random模塊
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
>>> list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> random.sample(list, 5)
[2, 5, 7, 8, 10]  # 運行結果
>>> random.sample(list, 5)
[9, 5, 10, 8, 6]  # 運行結果
>>> print(list)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # 原數組不發生改變

random.shuffle 將L數組中數字打亂順序輸入

>>> import random  # 導入Random模塊
>>> L=[1,2,3,4,5,6,7]
>>> random.shuffle(L)
>>> print(L)
[2, 3, 5, 7, 1, 6, 4]  # 原數組發生改變

from random import random* 暫時不知道怎麼用?

>>> from random import random
>>> a,b,c=random(),random(),random()
>>> import random
>>> print(random.random())
0.8400323649213723
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章