如何优雅地完成(Pythonic方式)
您有两个矩阵A和B,每个矩阵由一个列表列表。
您想计算A和B的元素乘积矩阵的总和。
示例代码:
sum = 0
nrows = len(A)
ncols = len(A[0])
for i in range(nrows):
for j in range(ncols):
sum += A[i][j]*B[i][j]
# interested finally in the value of sum
# return sum
例如
A = [[1,2,3],[3,4,5]]
和
B = [[3,2,2],[1,1,1]]
结果是:
1 * 3 + 2 * 2 + 3 * 2 + 3 * 1 + 4 * 1 + 5 * 1 = 25
答案 0 :(得分:4)
答案 1 :(得分:3)
您也可以尝试这样的事情(假设矩阵是2D):
import itertools
A=[[1,2,3],[3,4,5]]
B=[[3,2,2],[1,1,1]]
def flatten(lst):
return list(itertools.chain.from_iterable(lst))
>>> print(sum(x * y for x, y in zip(flatten(A), flatten(B))))
25
甚至:
>>> print(sum(x * y for x, y in zip(sum(A, []), sum(B, []))))
25
答案 2 :(得分:2)
这是@ MadPhysicist的生成器expr的平面版本。
sum(a*b for ab in zip(A, B) for a, b in zip(*ab))
# 25
答案 3 :(得分:1)
import itertools
A = [[1,2,3],[3,4,5]]
B = [[3,2,2],[1,1,1]]
# flatten list A => [1,2,3,3,4,5]]
A_flat = itertools.chain.from_iterable(A)
# flatten list B = > [3,2,2,1,1,1]]
B_flat = itertools.chain.from_iterable(B)
# making sum of 1+3 , 2+2 , 3+2 result=> [4, 4, 5, 4, 5, 6]
pair_sum = [ sum(pair) for pair in zip(A_flat,B_flat)]
# total
print('Total : ', sum(pair_sum))
############
import itertools
A = [[1,2,3],[3,4,5]]
B = [[3,2,2],[1,1,1]]
A_flat = itertools.chain.from_iterable(A)
B_flat = itertools.chain.from_iterable(B)
total = sum(sum(pair) for pair in zip(A_flat,B_flat))
print(total)