Python:如何在两个列表中对元素进行乘法和求和(不使用库)?

时间:2015-07-13 18:43:39

标签: python list

我有两个包含数字列表的列表(m1和m2)。我正在尝试按元素方式进行乘法和求和,包括交叉乘积以获得最终列表(结果)如下:

m1 = [[1, 2, 3], [4, 5, 6]]
m2 = [[7, 9, 2], [8, 1, 3]]

[[1*7+2*9+3*2,1*8+2*1+3*3],[4*7+5*9+6*2,4*8+5*1+6*3]]

result = [[31,19],[85,55]]

3 个答案:

答案 0 :(得分:5)

您可以使用python built-in functions和嵌套列表理解:

>>> [[sum(t*k for t,k in zip(i,j)) for j in m2] for i in m1]
[[31, 19], [85, 55]]

您还可以使用itertools.product查找子列表之间的产品:

>>> from itertools import product
>>> [sum(t*k for t,k in zip(i,j)) for i,j in product(m1,m2)]
[31, 19, 85, 55]

答案 1 :(得分:3)

让我们把问题分解成更小的部分。在最低级别,我们有两个小列表:[1, 2, 3][7, 9, 2],并希望逐个项目相乘:

item1 = [1, 2, 3]
item2 = [7, 9, 2]
zip(item1, item2)                        # ==> [(1, 7), (2, 9), (3, 2)]
[x * y for x, y in zip(item1, item2)]    # ==> [7, 18, 6]
sum(x * y for x, y in zip(item1, item2)) # ==> 31

现在,我们可以在双循环中使用它:

[[sum(x * y for x, y in zip(item1, item2)) for item2 in m2] for item1 in m1]
# ==> [[31, 19], [85, 55]]

答案 2 :(得分:0)

如果你想要它而不导入任何模块,你可以这样做:

>>> m1 = [[1, 2, 3], [4, 5, 6]]
>>> m2 = [[7, 9, 2], [8, 1, 3]]
>>> [[sum(map(lambda (s,t):s*t, zip(x,y))) for y in m2] for x in m1]
[[31, 19], [85, 55]]