我有两个嵌套列表:
a = [[1,2,3],[2,4,2]]
b = [[5,5,5],[1,1,1]]
我想繁殖并SUMPRODUCT每组元素得到
c = [[30],[8]]
= [[1*2+2*5+3*5],[2*1,4*1,2*1]]
我试过了:
c = sum(x * y for x, y in zip(a, b))
但我得到“不能通过类型'列表'的非int来加倍序列”
是否有一种简单的列表理解方法可以避免循环?
答案 0 :(得分:1)
没有numpy
列表理解的解决方案,也许会这样:
a = [[1,2,3],[2,4,2]]
b = [[5,5,5],[1,1,1]]
c = [[sum(map(lambda m: reduce(lambda h,i: h * i, m), n))] for n in [zip(x, y) for x, y in zip(a, b)]]
告诉我:
[[30], [8]]
另一个更简洁的解决方案是简单的for循环
a = [[1,2,3],[2,4,2]]
b = [[5,5,5],[1,1,1]]
c = []
for x, y in zip(a, b):
temp = []
for m, n in zip(x,y):
temp.append(m * n)
c.append([sum(temp)])
结果:
[[30], [8]]
对于不可读的变量名称,我建议在这种情况下使用简单的for
答案 1 :(得分:1)
您可以实施dotproduct
itertools recipes:
import operator
def dotproduct(vec1, vec2):
return sum(map(operator.mul, vec1, vec2))
代码
a = [[1,2,3], [2,4,2]]
b = [[5,5,5], [1,1,1]]
[[dotproduct(x, y)] for x, y in zip(a, b)]
# [[30], [8]]
答案 2 :(得分:0)
你可以使用嵌套列表理解来完成它,但它会很复杂。这是一步一步。
a = [[1,2,3],[2,4,2]]
b = [[5,5,5],[1,1,1]]
result1 = [[x*y for x, y in zip(r1, r2)] for r1, r2 in zip(a, b)]
c = [[sum(r)] for r in result1]
c
[[30], [8]]
答案 3 :(得分:0)
Numpy解决方案
import numpy as np
c = map(lambda x: sum(np.prod((np.array(x)), axis=0)), zip(a,b))
[30, 8]
如果您需要生成[[30], [8]]
,那么
c = map(lambda x: [sum(np.prod((np.array(x)), axis=0))], zip(a,b))