Python常用函式與技巧總結(二)

2021-08-10 08:58:48 字數 1717 閱讀 8084

列表生成式

a=[i for i in range(0,5)]

print(a)

[0,1,2,3,4]
filter(function,iterable) 過濾器

list(filter(lambda x:x%2,range(10)))
維度shape

shape[0] 橫向幾行

shape[1] 縱向幾列

[[5 10 15]

[20 25 30]]

a=np.array([5,10,15],[20,25,30])

print(a.shape[0])

輸出:2

vector=numpy.array([5,10,15,20])

print(vector[vector==10])

輸出:10

vector=numpy.array([5,10,15,20])

print(vector.sum())

輸出:50

matrix=numpy.array([

[5,10,15],

[20,25,30],

[35,40,45]

])matrix.sum(axis=1)

輸出:[30,75,120]

初始化陣列

a=np.arange(15).reshape(3,5)
a

[[0 1 2 3 4]

[5 6 7 8 9]

[10 11 12 13 14]]

陣列值相乘與矩陣乘運算

值相乘單純是對應值乘到一起

矩陣乘運算是按矩陣乘法規則運算

a=np.array([[1,1],

[0,1]])

b=np.array([[2,0],

[3,4]])

a*b

a.dot(b)

np.dot(a,b)

快速構造陣列 a=np.arange(15).reshape(3,5)

np.floor() 向下取整

b is a 即b和a代表同乙個矩陣,操作也同步

b=a.copy()複製乙個出來

np.argsort()元素排序

z[1::2,0::2]=1 從第1號行起每第二個等於1

歸一化操作

(z-min)/(max-min)

z=10*np.random.random((5,5))

zmin,zmax=z.min(),z.max()

z=(z-zmin)/(zmax-zmin)

交換矩陣,第0行和第1行:

a[[0,1]]=a[[1,0]]
找出陣列中與給定值最接近的數:

np.abs(z-a).argmin() #絕對值的最小值
np中判斷是否是空值np.isnan

pd中pd.isnull

列表轉換成字串用join()

""

.join(list(s))

Python常用小技巧總結

1.獲取本地mac位址 import uuid mac uuid.uuid1 hex 12 print ma程式設計客棧c 執行結果 e0cb4e077585 2.del 的使用 a b c d del a 0 print a 輸出 c d a b c d del a 0 2 刪除從第1個元素開始,...

python常用函式總結

1 python中struct.pack 和struct.unpack 用法詳細說明 2 找到列表裡長度最大的詞語 max m names key len 3 建立單詞和索引的對映 chars 為單詞集合 res dict c,i for i,c in enumerate chars 4 實現名稱l...

常用技巧總結

number轉string 需要標頭檔案 include string str to string number string轉number 需要標頭檔案 include 轉整形 int number atoi 1234 轉浮點 float number atof 123.123 需要標頭檔案 in...