比较列表python的列表元素

时间:2018-06-27 15:59:03

标签: python list

我有一个列表列表,我需要比较所有元素的项目0和项目2。如果这些项目相等,则我想对项目1和项目3求和。

list1 = [['diez.hn','Arts','Austria','8'], ['diez.hn','Entertainment','Austria','12']]
element 0 of list1: ['diez.hn','Arts','Austria','8']
element 1 of list1: ['diez.hn','Entertainment','Austria','12']

我需要什么:

list_ok = [['diez.hn','Arts - Entertainment','Austria','20']]

我尝试过这样的事情:

reader = [['diez.hn','Arts','Austria','8'], ['diez.hn','Entertainment','Austria','12']]
reader2 = [['diez.hn','Arts','Austria','8'], ['diez.hn','Entertainment','Austria','12']]
    for item in reader:
        for item2 in reader2:
            if item[0] and item[2] == item2[0] and item2[2]:
                item[1] = item[1] + item2[1]
                item[3] = item[3] + item2[3]

1 个答案:

答案 0 :(得分:5)

此方法对列表进行排序,然后使用itertools.groupby()对在位置0和2上具有相同元素的子列表进行分组:

import itertools
import operator

list1.sort(key=operator.itemgetter(0, 2))

list_ok = []

for k, group in itertools.groupby(list1, key=operator.itemgetter(0, 2)):
    group = list(group)
    list_ok.append([
        k[0], 
        ' - '.join(item[1] for item in group), 
        k[1], 
        str(sum(int(item[3]) for item in group)), 
    ])