根据比较在列表的Python列表中添加元素

| 我有一个列表列表,看起来像这样:
[\'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]和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
我花了一些时间来解决这个问题。任何帮助将不胜感激。     
已邀请:
        正是有一个功能用于此目的:
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()
。)     

要回复问题请先登录注册