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

2024-10-01 04:50:43 发布

您现在位置: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]相加。在

如果没有匹配项,则返回行如下:

^{pr2}$

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

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

我在这上面花了一点时间,这让我烦透了。任何帮助都将不胜感激。在


Tags: 列表cashtdrowusdtransactionsprintsales
1条回答
网友
1楼 · 发布于 2024-10-01 04:50:43

有一个函数正是为了这个目的:^{}。在

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

印刷品

^{pr2}$

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

相关问题 更多 >