二维数组Python部分的和列

时间:2017-06-16 20:37:58

标签: python arrays matrix sum calculated-columns

如果两个第一列匹配,如何获取最后两列的总和?

输入:

 M =   [[1,1,3,5],
        [1,1,4,6],
        [1,2,3,7],
        [1,2,6,6],
        [2,1,0,8],
        [2,1,3,5],
        [2,2,9,6],
        [2,2,3,4]]

输出:

M = [[1,1,7,11],
    [1,2,9,13],
    [2,1,3,13],
    [2,2,12,10]]

你可以用for循环吗?

3 个答案:

答案 0 :(得分:0)

假设有两个相似的列表相互跟随,您总是可以迭代M[:-1],然后根据下一个列表值检查当前列表值

M =[[1,1,3,5],[1,1,4,6],[1,2,3,7],[1,2,6,6],[2,1,0,8],[2,1,3,5],[2,2,9,6],[2,2,3,4]]
t=[]
for i,m in enumerate(M[:-1]):
  if m[0] == M[i+1][0] and m[1]==M[i+1][1]:
    t.append([m[0],m[1],m[2]+M[i+1][2],m[3]+M[i+1][3]])
print(t)
#[[1, 1, 7, 11], [1, 2, 9, 13], [2, 1, 3, 13], [2, 2, 12, 10]]

如果订单可能被加扰,我会使用2个for循环。第二个将检查m后面的每个其他列表(它不需要检查它们,因为他们检查了它)。

for i,m in enumerate(M[:-1]):
  for x,n in enumerate(M[i+1:]):
    if m[0] == n[0] and m[1]==n[1]:
      t.append([m[0],m[1],m[2]+n[2],m[3]+n[3]])

答案 1 :(得分:0)

我们可以在前两列中找到唯一的元组,然后迭代这些元组以查找行等于元组的每列的总和。

不确定最快的解决方案是什么,但这是一个选择:

M =[[1,1,3,5],[1,1,4,6],[1,2,3,7],[1,2,6,6],[2,1,0,8],[2,1,3,5],[2,2,9,6],[2,2,3,4]]

ans = []
for vals in list(set((x[0], x[1]) for x in M)):
    ans.append([vals[0], vals[1], sum(res[2] for res in M if (res[0], res[1]) == vals), sum(res[3] for res in M if (res[0], res[1]) == vals)])

答案 2 :(得分:0)

具有列表理解和itertools'groupby的解决方案:

from itertools import groupby

M = [
    [1,1,3,5],
    [1,1,4,6],
    [1,2,3,7],
    [1,2,6,6],
    [2,1,0,8],
    [2,1,3,5],
    [2,2,9,6],
    [2,2,3,4],
]

print([
    [
        key[0],
        key[1],
        sum(x[2] for x in group),
        sum(x[3] for x in group),
    ]
    for key, group in [
        (key, list(group))
        for key, group in groupby(sorted(M), lambda x: (x[0], x[1]))
    ]
])

结果:

[[1, 1, 7, 11], [1, 2, 9, 13], [2, 1, 3, 13], [2, 2, 12, 10]]

reduce可以简化为:

from itertools import groupby
from functools import reduce

M = [
    [1,1,3,5],
    [1,1,4,6],
    [1,2,3,7],
    [1,2,6,6],
    [2,1,0,8],
    [2,1,3,5],
    [2,2,9,6],
    [2,2,3,4],
]

print([
    reduce(
        lambda x, y: [y[0], y[1], y[2] + x[2], y[3] + x[3]],
        group,
        (0, 0, 0, 0),
    )
    for _, group in groupby(sorted(M), lambda x: (x[0], x[1]))
])