Python:从列表列表添加值

2024-04-19 06:40:12 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我的名单

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)

请告诉我。你知道吗


Tags: andinreffalse列表fordbif
3条回答

在这里,我使用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)]
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()])

使用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)]

^{}。你知道吗

相关问题 更多 >