我需要迭代字段并按照另一列中的值计算少数列的总和。
对于ex基表是
C1 C2 C3 C4 C5
a1 2 3 4 q
a1 4 5 7 a
a2 34 56 6 e
a2 4 5 5 5
a3 3 3 3 4
a3 3 3 3 3
结果表应为
c2 c3 c4
a1 6 8 11
a2 38 61 11
a3 6 6 6
50 75 28
我能够迭代字段以获取每个字段的值,但却陷入了创建结果格式的二维矩阵的困境。我正在研究二维数组来实现这种情况。
答案 0 :(得分:0)
在这里做了很多假设,因为这个问题非常不明确......
# table containing only the actual data
table = [[2,3,4,"q"],[4,5,7,"a"],[34,56,6,"e"],[4,5,5,5],[3,3,3,4],[3,3,3,3]]
result = []
# iterate through table[0/2/4/...] zipped together with table[1/3/5/...]
for (row1, row2) in zip(table[::2], table[1::2]):
# add the first three elements of each row and append the results to our result
result.append([c1+c2 for c1,c2 in zip(row1[:3], row2[:3])])
print(result)
输出
[[6, 8, 11], [38, 61, 11], [6, 6, 6]]