python常用模組 random模組

2022-03-14 08:22:53 字數 3286 閱讀 3772

參考部落格:

今天突然想起python該怎麼生成隨機數?查了一下,貼出實驗結果

首先要匯入import這個模組

random模組中常用的函式

random()

隨機生成乙個浮點數,範圍在0到1之間

uniform()

隨機生成指定範圍之內的浮點數

randint()

隨機生成指定範圍之內的整數

randrange()

隨機生成指定範圍之內的整數,可以指定步長

choise()

隨機從乙個序列中選擇乙個元素

shuffle()

將列表的順序打亂

sample()

隨機獲取序列中指定的數量的元素

1.random.random():隨機生成乙個浮點數,範圍在0<=x<=1.0

>>>random.random()

0.7802959818148015

>>>random.random()

0.328008839087651

>>>random.random()

0.5568708122526114

>>>random.random()

0.23048925282509325

2.random.uniform():隨機生成指定範圍內的隨機浮點數。

>>> random.uniform(18,15)  a >b a16.01770569291661

>>> random.uniform(18,15)

17.027730377035027

>>> random.uniform(10,15)

14.682052726572774

>>> random.uniform(10,15)

12.997092389884806

3.random.randint():隨機選取乙個範圍內的整數

>>> random.randint(12,14)

12>>> random.randint(12,16)

14>>> random.randint(12,16)

16

4.random.randrange():和randranint()類似,返回範圍內的乙個整數,randrange()可以指定數值的步長。

>>> random.randrange(10,100)

97>>> random.randrange(10,100) #

步長預設1

89>>> random.randrange(10,100,2)

66>>> random.randrange(10,100,2)

52>>> random.randrange(10,1,2) #

第乙個數必須小於第二個數

traceback (most recent call last):

file

"", line 1, in

file

"/usr/local/python3.6/lib/python3.6/random.py

", line 212, in

randrange

raise valueerror("

empty range for randrange()")

valueerror: empty range

for randrange()

5.random.chiose():隨機選取序列中的乙個元素

>>> random.choice(('

kebi

','maoxina

','xinye'))

'xinye

'>>>

>>> random.choice(('

kebi

','maoxina

','xinye'))

'kebi

'>>> random.choice([1,2,3,4])

2>>> random.choice([1,2,3,4])

2>>> random.choice("

老男孩it教育")

'育'>>> random.choice("

老男孩it教育")

'男'

6.random.shuffle():將列表中的乙個元素打亂

>>> name = ['

kebi

','喜歡

','豬']

>>>random.shuffle(name)

>>>name['

喜歡', '

豬', '

kebi']

>>>random.shuffle(name)

>>>name['

kebi

', '

喜歡', '豬'

]>>>random.shuffle(name)

>>>name['

喜歡', '

豬', '

kebi

']

7.random.sample():隨機獲取序列中指定數量的元素

>>> ss = (1,2,3,4)

>>> sst = '

woshishui

'>>> random.sample(ss,2)

[2, 4]

>>> random.sample(ss,2)

[2, 1]

>>> random.sample(sst,1)['

h']>>> random.sample(sst,4) #

不是切片,沒有順序['o

', '

u', '

i', 'w'

]>>> random.sample(name) #

必須要指定數量

traceback (most recent call last):

file

"", line 1, in

typeerror: sample() missing 1 required positional argument: 'k'

>>> random.sample(name,2)['

豬', '喜歡'

]>>> random.sample(name,1)['

豬']

Python常用模組 隨機數模組(random)

python常用模組 隨機數模組 random 一.常用方法舉例 1 usr bin env python2 coding utf 8 3 author yinzhengjie4 blog email y1053419035 qq.com67 import random 8print random....

Python順序與range和random

range start,stop step start是開始,stop是停下,step是步長。range 10 range 0,10 list range 10 生成乙個0到9之間的序列 0,1,2,3,4,5,6,7,8,9 list range 1,10 生成1到9的序列 1,2,3,4,5,6...

python 常用模組

1.告訴直譯器 找模組 import sysunix要絕度路徑 只有第一次匯入執行。name main 2.當做包,必須包含乙個命名為 init py的檔案 模組 3.dir看模組裡有什麼 下劃線開始,不是給模組外部用的。過濾 import copy n for n in dir copy if n...