2011-06-13 154 views
0

我的目錄列表看起來像這樣:添加元素

['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] THEN總結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 

我花了一點時間就這個問題和它的竊聽的廢話了我。任何幫助將不勝感激。

回答

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()。 )