python np python np 函式的運用

2021-10-12 11:04:14 字數 1921 閱讀 6574

1、np.random.rand 用於生成[0.0, 1.0)之間的隨機浮點數, 當沒有引數時,返回乙個隨機浮點數,當有乙個引數時,返回該引數長度大小的一維隨機浮點數陣列,引數建議是整數型,因為未來版本的numpy可能不支援非整形引數。

import numpy as np

>>> np.random.rand(10)

array([ 0.89103033, 0.60550521, 0.13856488, 0.57468244, 0.370697 ,

0.31823162, 0.58358377, 0.97177935, 0.76400592, 0.11269547])

2、np.random.randn該函式返回乙個樣本,具有標準正態分佈。

>>> np.random.randn(10)

array([-0.42625455, -1.86248727, 0.96323332, -0.32809754, -0.79697695,

-0.07145189, 2.89728643, 2.32095237, 1.12925633, -0.39210317])

3、np.random.randint(low[, high, size]) 返回隨機的整數,位於半開區間 [low, high)。

>>> np.random.randint(10,size=10)

array([4, 1, 4, 3, 8, 2, 8, 5, 8, 9])

4、random_integers(low[, high, size]) 返回隨機的整數,位於閉區間 [low, high]。

>>> np.random.random_integers(5)

5、 np.random.shuffle(x) 類似洗牌,打亂順序;np.random.permutation(x)返回乙個隨機排列

>>> arr = np.arange(10)

>>> np.random.shuffle(arr)

>>> arr

[1 7 5 2 9 4 3 6 0 8]

>>>> np.random.permutation(10)

array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])

二. 用random模組自己構造

1、random.randint(low, hight) -> 返回乙個位於[low,hight]之間的整數該函式接受兩個引數,這兩個引數必須是整數(或者小數字是0的浮點數),並且第乙個引數必須不大於第二個引數

>>> import random

>>> random.randint(1,10)

>>> random.randint(1.0, 10.0)

2、random.random() -> 不接受引數,返回乙個[0.0, 1.0)之間的浮點數

>>> random.random()

0.5885821552646049

3、random.uniform(val1, val2) -> 接受兩個數字引數,返回兩個數字區間的乙個浮點數,不要求val1小於等於val2

>>> random.uniform(1,5.0)

4.485403087612088

>>> random.uniform(9.9, 2)

5.189511116007191

4、random.randrange(start, stop, step) -> 返回以start開始,stop結束,step為步長的列表中的隨機整數,同樣,三個引數均為整數(或者小數字為0),若start大於stop時 ,setp必須為負數.step不能是0.

>>> random.randrange(1, 100, 2) #返回[1,100]之間的奇數

>>> random.ranrange(100, 1, -2) #返回[100,1]之間的偶數

5、生成隨機數組

方法,使用random.ranident,構造乙個列表即可:

for迴圈 len函式和range函式的運用

函式 len 作用 返回字串 列表 字典 元組等長度 語法 len str 引數 str 要計算的字串 列表 字典 元組等 返回值 字串 列表 字典 元組等元素的長度 例項1 計算字串的長度 s hello word len s 92 計算列表的元素個數 str h e l l o len str ...

python函式內計時 Python函式執行計時

python函式計時 使用threading的timer定時器 from threading import timer import time def time limit interval def wraps func def time out raise runtimeerror def dec...

workerman怎樣統計框架裡的函式執行情況

不同的框架,略有不同。首先,在index.php檔案中,需要加入。載入vendor,統計服務 rpc client等.require dir vendor bootstrap autoloader.php bootstrap autoloader instance addroot dir init ...