开发者

Adding elements within a Python list of list based on a comparison

I have a list of list that looks like this:

['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']

Essentially, I want to perform a logic where the current and next rows are being checked based on matching elements. So, if currentRow[0] == nextRow[0] AND currentRow[1] == nextRow[1] THEN sum up currentRow[2] and nextRow[2].

If no match is made, then just return the row like so:

['000000000000012', 'AUD ', '      -1500000.0000']
['000000000000012', 'BRL ', '          6070.5400']
['000000000000012', 'MXN ', '      19524996.5400']
['000000000000012', 'USD ', '        225435.56'] <=== this row is summe开发者_开发知识库d

The list of list is already sorted so, I would imagine, this makes life easier. The resulting output can be appended into a list but formatting doesn't have to as I can always re-apply it on the outbound side. For laughs, this is what I have so far:

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

I've spent a bit of time on this and it's bugging the crap out of me. Any help would be GREATLY appreciated.


There is a function for exactly this purpose: itertools.groupby().

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

prints

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

(Note that I used my_list for the name of the list since your name max does not seem to be a good choice -- it shadows the built-in name max().)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜