基于比较在Python列表中添加元素

时间:2011-06-13 20:44:02

标签: python list element sum

我有一个列表如下:

['000000000000012', 'AUD ', '      -1500000.0000', '29473550', 'TD CASH', 'Currencies', 'Unsettled Transactions', 'Unsettled']
['000000000000012', 'BRL ', '          6070.5400', '        ', 'TD CASH', 'Beginning Balance', 'Positions', 'Settled']
['000000000000012', 'MXN ', '      19524996.5400', '        ', 'TD CASH', 'Beginning Balance', 'Positions', 'Settled']
['000000000000012', 'USD ', '          9937.92', '29473153', 'TD CASH', 'Sales', 'Unsettled Transactions', 'Unsettled']
['000000000000012', 'USD ', '          9937.92', '29473155', 'TD CASH', 'Sales', 'Unsettled Transactions', 'Unsettled']
['000000000000012', 'USD ', '        100252.78', '29473080', 'TD CASH', 'Sales', 'Unsettled Transactions', 'Unsettled']
['000000000000012', 'USD ', '        105306.94', '29473142', 'TD CASH', 'Sales', 'Unsettled Transactions', 'Unsettled']

基本上,我想执行一个逻辑,根据匹配元素检查当前行和下一行。所以,如果currentRow [0] == nextRow [0] AND currentRow [1] == nextRow [1]那么总结currentRow [2]和nextRow [2]。

如果没有匹配,那么只需返回行:

['000000000000012', 'AUD ', '      -1500000.0000']
['000000000000012', 'BRL ', '          6070.5400']
['000000000000012', 'MXN ', '      19524996.5400']
['000000000000012', 'USD ', '        225435.56'] <=== this row is summed

列表清单已经排序了,我想,这会让生活更轻松。结果输出可以附加到列表中,但格式不必,因为我总是可以在出站端重新应用它。对于笑,这是我到目前为止所做的:

prevAcct = None
prevCurr = None
finalSum = 0
for row in max:
    if(str(row[0]).strip() == prevAcct and str(row[1]).strip() == prevCurr):
        #print row[0]
        #print row[1]
        finalAcct = str(row[0]).strip()
        finalSum = eval(row[1]) + eval(finalSum)
    else:
        print "Setting new account and currency!"
        prevAcct = row[0]
        prevCurr = row[1]
        print "DEBUG: " + prevAcct + " and " + prevCurr

我已经花了一些时间在这上面,它正在惹恼我。任何帮助都会非常感激。

1 个答案:

答案 0 :(得分:4)

正是出于这个目的的功能:itertools.groupby()

print [key + [sum(float(x[2]) for x in it)]
       for key, it in groupby(my_list, lambda x: x[:2])]

打印

[['000000000000012', 'AUD ', -1500000.0],
 ['000000000000012', 'BRL ', 6070.54],
 ['000000000000012', 'MXN ', 19524996.539999999],
 ['000000000000012', 'USD ', 225435.56]]

(请注意,我使用my_list作为列表名称,因为您的名称max似乎不是一个好选择 - 它会影响内置名称max()。 )