Python:从列表列表中添加值

时间:2015-06-07 10:38:42

标签: python python-2.7

下面是我的清单列表;

db_rows = [('a','b','c',4),
           ('a','s','f',6),
           ('a','c','d',6),
           ('a','b','f',2),
           ('a','b','c',6),
           ('a','b','f',8),
           ('a','s','f',6),
           ('a','b','f',7),
           ('a','s','f',5),
           ('a','b','f',2)]

如果内部列表中前三个值相同,那么我需要添加第四个值来创建新列表

我需要这样的结果列表:

final_list = [('a','b','c',10),
              ('a','s','f',17),
              ('a','c','d',6),
              ('a','b','f',19)]

我尝试过以下脚本(不工作):

final_list = []
for row in db_rows:
    temp_flag=False
    temp_list = []
    val = 0
    for ref_row in db_rows:
        if row != ref_row:
            if row[0]==ref_row[0] and row[1]==ref_row[1] and row[2]==ref_row[2]:
                val = val + ref_row[3]
                temp_flag=True
    temp_list=(row[0],row[1],row[2],val)
    if temp_flag==False:
        temp_list=row
    final_list.append(temp_list)
请告诉我。

3 个答案:

答案 0 :(得分:5)

使用字典作为Dov Grobgeld评论,然后将字典转换回列表。

from collections import defaultdict

db_rows = [('a','b','c',4),
           ('a','s','f',6),
           ('a','c','d',6),
           ('a','b','f',2),
           ('a','b','c',6),
           ('a','b','f',8),
           ('a','s','f',6),
           ('a','b','f',7),
           ('a','s','f',5),
           ('a','b','f',2)]

sums = defaultdict(int)
for row in db_rows:
    sums[row[:3]] += row[3]

final_list = [key + (value,) for key, value in sums.iteritems()]

打印final_list输出:

[('a', 'b', 'c', 10), ('a', 's', 'f', 17), ('a', 'b', 'f', 19), ('a', 'c', 'd', 6)]

请参阅collections.defaultdict

答案 1 :(得分:1)

from collections import defaultdict
db_rows = [('a','b','c',4),
           ('a','s','f',6),
           ('a','c','d',6),
           ('a','b','f',2),
           ('a','b','c',6),
           ('a','b','f',8),
           ('a','s','f',6),
           ('a','b','f',7),
           ('a','s','f',5),
           ('a','b','f',2)]

d = defaultdict(int)


for ele in db_rows:
    d[ele[:-1]] += ele[-1]

print([(k +(v,)) for k,v in d.items()])

答案 2 :(得分:0)

在这里,我使用OrderedDict来保留找到前三个值的顺序。

from collections import OrderedDict

db_rows = [('a','b','c',4),
           ('a','s','f',6),
           ('a','c','d',6),
           ('a','b','f',2),
           ('a','b','c',6),
           ('a','b','f',8),
           ('a','s','f',6),
           ('a','b','f',7),
           ('a','s','f',5),
           ('a','b','f',2)]

temp_dict = OrderedDict()

for x in db_rows:
    temp_dict[x[:3]] = temp_dict.get(x[:3], 0) + x[3]

final_list =  [k +(v,) for k,v in temp_dict.iteritems()]

我们现在可以检查final_list的值,它会按照上面提到的顺序给出所需的结果。

final_list
[('a', 'b', 'c', 10),
 ('a', 's', 'f', 17),
 ('a', 'c', 'd', 6),
 ('a', 'b', 'f', 19)]