L = []
def my_func(x):
return 2*x
for i in range(5):
L.append(my_func(i))
print(L)
[my_func(i) for i in range(5)]
# 加if条件1
[my_func(i) for i in range(5)if i % 2 == 0] #先if后for 即(0,5)偶数乘2
# if条件2
[my_func(i) if i % 2 == 0 else i for i in range(5)] #先if后for 即(0,5)偶数乘以2 奇数不变
#嵌套
[m+'_'+n for m in ['a', 'b'] for n in ['c', 'd']]
#多个for
[x*y for x in [1,2,3,4] for y in [2,4,6,8]]
a, b = 'cat', 'dog'
condition = 2 > 1 # 此时为 True
if condition:
value = a
else:
value = b
value
value = 'cat' if 2>1 else 'dog'
value
f = lambda x,y:x**2 + y**2
f(3,4)
[(lambda x: 2*x)(i) for i in range(5)]
a = map(lambda x: 2*x, range(5))
a
a = list(range(5))
b = list(map(lambda x: 2*x, a))
print(a)
print(b) #看出map()不改变原有的 list,而是返回一个新的 list
list(map(lambda x, y: str(x)+'_'+y, range(5), list('abcde')))
list(map(lambda x, y: x**2 + y**2, [3,6,12], [4,8,5]))
xf = [1,2,3,4,5,6,7] # 7 个元素
yf = [2,3,4,5,6,7] # 6 个元素
zf = [1,1,1,1,1] # 5 个元素
k = list(map(lambda x,y,z : x + y + z,xf, yf, zf))
k # 5个
L1, L2, L3 = list('abc'), list('def'), list('hij') #列表打包
a = list(zip(L1, L2, L3))
a
b = list(zip(*a)) # * 解压
b
c = tuple(zip(L1, L2, L3)) #元组打包
c
d = tuple(zip(*c)) # 解压
d
brands = ["苹果","华为","oppo"]
typess = ["12pro","mate40pro","find x2 pro"]
cpus = ["A14","麒麟9000","骁龙865"]
oss = ["ios","Android"]
for brand,types,cpu in zip(brands,typess,cpus):
print('{}{}的处理器:{}'.format(brand,types,cpu))
#元素个数不一致 返回的对象长度与最短的可迭代对象相同 oppo没了
for brand,types,cpu,os in zip(brands,typess,cpus,oss):
print('{}{}的处理器:{},搭载系统:{}'.format(brand,types,cpu,os))
for index, value in enumerate(brands):
print(index, value)
for index, value in zip(range(len(cpus)),cpus):
print(index, value)
dict(zip(brands, cpus))
import numpy as np #array构造数组或矩阵
x = np.array(([1,2,3],
[4,5,6],
[7,8,9]))
x
a = np.linspace(1,5,11) # 起始、终止(包含)、样本个数
b = np.arange(1,5,2) # 起始、终止(不包含)、步长
print(a)
print(b)
np.zeros((2,3)) # 传入元组表示各维度大小 返回来一个给定形状和类型的用0填充的数组
np.eye(3) # 3*3 的单位矩阵
np.eye(3, k=1) # 偏移主对角线 1 个单位的伪单位矩阵
np.full((2,3), 10) # 元组传入大小,10 表示填充数值
np.full((2,3), [1,2,3]) # 通过传入列表填充每行的值
np.random.rand(3) # 生成服从 0-1 均匀分布的三个随机数
np.random.rand(3, 3) # 注意这里传入的不是元组,每个维度大小分开输入
a, b = 5, 15
(b - a) * np.random.rand(3) + a #服从区间 a 到 b 上的均匀分布 **注**
np.random.randn(3)
sigma, mu = 2.5, 3
mu + np.random.randn(3) * sigma
low, high, size = 5, 15, (2,2)
np.random.randint(low, high, size)
import numpy as np
brands = ["苹果","华为","OPPO","小米"]
np.random.choice(brands, 4, replace=False, p=[0.1, 0.7, 0.1 ,0.1])
np.random.choice(brands, 4, p=[0.1, 0.7, 0.1 ,0.1])
import random
random.sample(brands,3)
print(brands)
print(np.random.permutation(brands))
print(brands) #原列表不变
np.random.shuffle(brands)
print(brands) #改变原列表
x = np.eye(2,3)
x
x.T
print(np.r_[x,x])
print(np.c_[x,x])
print(np.vstack((x,x)))
print(np.hstack((x,x)))
print("______________________________________")
print(np.concatenate((x,x),axis=0))
print(np.concatenate((x,x),axis=1))
X = np.arange(12).reshape(3,4)
X
X.reshape((2,6),order='C') ## 按照行读取和填充
X.reshape((2,6),order='F') ## 按照列读取和填充
X.reshape((2,-1))
target = np.ones((3,1))
print(target)
print(target.reshape(-1))
x = np.arange(12).reshape(3,4)
x
x[:-1, [0,3,2]]
x[::-2,0:3:2] #行倒过来 步长为2
x[np.ix_([True, False, True], [True, False, True,True])]
x[np.ix_([0,2], [True, False, True,True])]
y = x.reshape(-1) #转为一维数组
y[y%2==0]
import numpy as np
x = np.arange(10)
x
np.where(x%2 == 0,x,0) #条件为偶数成立 填充x中值否则为0
np.nonzero(x) #return 非0
print(np.argmax(x))
print(np.argmin(x))
print(x.any()) #序列至少存在一个True或非零元素时返回True
print(x.all()) #序列元素全为True或非零元素时返回True
x = np.arange(6)
print(x)
print(x.cumprod()) #累乘
print(x.cumsum()) #累加
print(np.diff(x)) ##表示和前一个元素做差
import numpy as np
x = np.arange(10)
print(x)
print("最大值:",x.max())
print("方差:",x.std())
print("0.5分位数:",np.quantile(x, 0.5))
x = np.append(np.arange(10),np.nan)
x
print(x.max())
print(np.nanmax(x))
a = np.array([1,3,4,5])
b = np.array([2,4,6,10])
print(np.cov(a, b)) #协方差cov()
print(np.corrcoef(a, b)) #相关系数corrcoef()
x = np.arange(12).reshape(3,-1)
print(x)
print(x.sum(0))
print(x.sum(1))
a = 2*np.eye(3,3)+1
print(a)
a = 1/a # 此处标量1扩展为大小为(3,3)数组
print(a)
res = np.ones((3,2))
print(res)
print(res * np.array([[2,3]])) # 3×2 与1×2相运算 将[2,3]一行变为三行
##哈达马积
res * np.array([[2],[3],[4]]) # 3×2 与3×1相运算 将一列变为两列
res * np.array([[2]]) # 3×2 与1×1相运算 等价于两次扩充
print(np.ones(3) + np.ones((2,3)))
print(np.ones(3) + np.ones((2,1)))
print(np.ones(1) + np.ones((2,3)))
import numpy as np
a = np.array([1,2,3])
b = np.array([1,3,5])
a.dot(b)
martix_target = np.arange(4).reshape(-1,2)
print(martix_target)
print(np.linalg.norm(martix_target, 'fro')) #F范
print(np.linalg.norm(martix_target, np.inf)) #
a = np.arange(4).reshape(-1,2)
b = np.arange(-4,0).reshape(-1,2)
print(a@b)
M1 = np.random.rand(2,3)
M2 = np.random.rand(3,4)
res = np.empty((M1.shape[0],M2.shape[1])) #shape(0)行数、shape(1)列数
for i in range(M1.shape[0]):
for j in range(M2.shape[1]):
item = 0
for k in range(M1.shape[1]):
item += M1[i][k] * M2[k][j]
res[i][j] = item
((M1@M2 - res) < 1e-15).all() # 排除数值误差
M1 = np.random.rand(2,3)
M2 = np.random.rand(3,4)
x = [[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])]
((M1@M2 - x) < 1e-15).all() # 排除数值误差
import numpy as np
A = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
print(A)
B = [[sum([A[i][j]*(1/A[i][k]) for k in range(3)])
for j in range(3)]
for i in range(3)]
B
A = np.arange(1,10).reshape(3,-1)
B = A*(1/A).sum(1).reshape(-1,1) #广播完美应用 sum(1)列求和
C = (1/A).sum(1).reshape(-1,1)
d = A*C
print(d)
print(B)
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
np.random.seed(0)
A = np.random.randint(10, 20, (8, 5))
B = A.sum(0)*A.sum(1).reshape(-1, 1)/A.sum() #妙 广播运用
X = ((A-B)**2/B).sum()
print(X)
np.random.seed(0)
m, n, p = 100, 80, 50
B = np.random.randint(0, 2, (m, p))
U = np.random.randint(0, 2, (p, n))
Z = np.random.randint(0, 2, (m, n))
def solution(B=B, U=U, Z=Z):
L_res = []
for i in range(m):
for j in range(n):
norm_value = ((B[i]-U[:,j])**2).sum()
L_res.append(norm_value*Z[i][j])
return sum(L_res)
solution(B, U, Z)
import numpy as np
a = np.array([3,2,1,2,3,4,6])
b = np.array([1,2,5,6,7])
c = np.array([3,2,1,2,3,4,6])
def ss(x):
b = np.sort(np.append(x,0))
cc = np.where(np.diff(b)==1)
cc = list(cc)
return len(cc[0])
print(ss(a))
print(ss(b)) #失败