(AI算法系列)
1.列表推导式
xxx for i in yyy
#xxx为映射函数,其输入为后面 i 指代的内容
#yyy表示迭代的对象
2.多层嵌套
xxx for m in yyy for n in zzz
#第一个for为外层循环
3.if条件赋值
value = a if xxx else b
my_func = lambda x:2*x
multi_para_func = lambda a,b :a+b
[(lambda x:2*x)(i) for i in range(5)]
#等价于
list(map(lambda x:2*x, range(5)))
list(map(lambda x, y: str(x)+'_'+y, range(5), list('abcde')))
L1, L2, L3 = list('abc'), list('def'), list('hij')
for i, j, k in zip(L1, L2, L3):
print(i, j, k)
L = list('abcd')
for idx,val in enumerate(L):
print(idx, val)
#等价于:
for idx,val in zip(range(len(L)),L):
print(idx, val)
dict(zip(L1,L2))
zipped = list(zip(L1,L2,L3))
list(zip(*zipped))
#[('a', 'b', 'c'), ('d', 'e', 'f'), ('h', 'i', 'j')]
import numpy as np
np.array([1,2,3])
(b - a) * np.random.rand(3) + a np.random.randn(2, 2)mu + np.random.randn(3) * sigma np.random.randint(low, high, size) np.random.choice(my_list, 2, replace=False, p=[0.1, 0.7, 0.1 ,0.1]) np.random.permutation(my_list) np.random.seed(0)
np.random.rand()
a.reshape(-1)将 n*1 大小的数组转为 1 维数组
res = [[sum([M1[i][k] * M2[k][j] for k in range(M1.shape[1])]) for j in range(M2.shape[1])] for i in range(M1.shape[0])]
np.abs((M1@M2 - res) < 1e-15).all()
A= np.arange(1,10).reshape(3,3)
B = A*(1/A).sum(1)#按行相加
A = np.random.randint(10, 20, (8, 5))
A.sum()#全部元素和,一个值
B = A.sum(0)* A.sum(1).reshape(-1,1)/ A.sum()#reshape为一列
C = ((A - B) ** 2/B).sum()
(((B ** 2).sum(1).reshape(-1,1) + (U ** 2).sum(0) - 2*B@U)*Z).sum()
# B是 m × p,按行加出p列 ,U是 p × n,按列加出p行,再运算
lambda x:np.diff(np.nonzero(np.r_[1,np.diff(x)!=1,1])).max()
无
无