带条件的列表推导式
even_number = [i for i in range(10) if i % 2 == 0]
even_number # output [0, 2, 4, 6, 8]
[0, 2, 4, 6, 8]
列表推导式的嵌套
matrix = [[i * j for i in range(1, 4)]for j in range(1, 4)]
matrix # output = [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
矩阵的转置
A = [[1, 2],
[2, 4],
[3, 6]]
B = [[A[j][i]
for j in range(len(A))]
for i in range(len(A[0])) ]
B
[[1, 2, 3], [2, 4, 6]]
矩阵的逐项积
def harmard_prod(V1, V2):
if(len(V1) != len(V2) or len(V1[0]) != len(V2[0])):
raise ValueError("Matrices must have the same shape")
result = [[V1[i][j] * V2[i][j]
for j in range(len(V1[0]))]
for i in range(len(V1))]
return result
A = [[1, 2],
[2, 4]]
B = [[1, 3],
[2, 6]]
harmard_prod(A,B)
[[1, 6], [4, 24]]
笛卡尔积
A = ['a', 'b', 'c']
B = [1, 2]
cartesian_product = [y+str(x) for x in B for y in A]
cartesian_product
['a1', 'b1', 'c1', 'a2', 'b2', 'c2']
矩阵的乘法
import numpy as np
A = [[1, 2, 3],
[4, 5, 6]]
B = [[1, 2],
[4, 5],
[6, 7]]
C = np.zeros((len(A), len(A)))
for i in range(len(A)): # 3
for j in range(len(B[0])): # 2
for k in range(len(A[0])):
C[i][j] += A[i][k] * B[k][j]
C
array([[27., 33.],
[60., 75.]])
标签:推导,python,矩阵,V2,len,V1,range
From: https://www.cnblogs.com/baidh/p/18118329