0

给定一个 [yyy,m,value] 列表,我需要添加与单个年份对应的所有值。以便,

A = [
[['2008', '3', '5'],['2008', '4', '35'],['2013', '3', '71']],
[['2008', '6', '2'],['2008', '7', '2'],['2008', '8', '4'],['2013', '3', '128']]
]

变成

A = [
[['2008', '40'],['2013','71']],
[['2008', '8'],['2013','128']]
]

最好的方法是什么?谢谢。

4

3 回答 3

2

使用defaultdict

from collections import defaultdict

b = []

for line in A:
    d = defaultdict(int)
    for entry in line:
        d[entry[0]] += int(entry[2])
    b.append([(k,str(v)) for k,v in sorted(d.items(),key=lambda x: int(x[0]))])

b
Out[71]: [[('2008', '40'), ('2013', '71')], [('2008', '8'), ('2013', '128')]]
于 2013-08-12T23:34:01.657 回答
0

您可以明确并使用一些简单的循环,如下所示:

A = [[['2008', '3', '5'],['2008', '4', '35'],['2013', '3', '71']],
[['2008', '6', '2'],['2008', '7', '2'],['2008', '8', '4'],['2013', '3', '128']]    ]

l,B,k=[],[],0

for x in A:
    for y in x:
        l.append(y[0])
    for z in set(l):
        for y in x:
             if y[0] == z:
                k += int(y[2])
        B.append([z,k])
        k=0
print B

这给出了预期:

>>>B
[['2008', 40], ['2013', 71], ['2008', 8], ['2013', 128]]
于 2013-08-12T23:39:03.587 回答
0

这有效:

for i,li in enumerate(A):
    d={}
    for sli in li:
        year=sli[0]
        d.setdefault(year,0)
        d[year]+=int(sli[-1])

    A[i]=[[k,str(d[k])] for k in sorted(d.keys())]

A的值被替换到位:

>>> A
[[['2008', '40'], ['2013', '71']], [['2008', '8'], ['2013', '128']]]
于 2013-08-13T00:15:09.757 回答