python中的列表列表

时间:2017-10-01 09:30:53

标签: python

如果给出两个列表,如下所示:

list1 = [['John',2],
         ['Smith',5],
         ['Kapil',3]]

list2 = [['Smith',2],
         ['John',2],
         ['Stephen',3]]

我想要一个如下列表:

final = [['John',4],
        ['Smith',7],
        ['Kapil',3],
        ['Stephen',3]]

如果在list1和list2中都出现了名称,它将包含数字的总和。

1 个答案:

答案 0 :(得分:1)

一种简单的方法是使用字典。像这样:

list1 = [['John',2],['Smith',5],['Kapil',3]]

list2 = [['Smith',2],['John',2],['Stephen',3]]

dict = {}

for item in list1:
    try:
        dict[item[0]] += item[1]
    except:
        dict[item[0]] = item[1]

for item in list2:
    try:
        dict[item[0]] += item[1]
    except:
        dict[item[0]] = item[1]

print dict

这给出了输出:

{'John': 4, 'Smith': 7, 'Kapil': 3, 'Stephen': 3}

然后将其转换为列表列表,其中包含以下内容:

results = []
for k, v in dict.items():
    results.append([k, v])

print results
# [['John', 4], ['Smith', 7], ['Kapil', 3], ['Stephen', 3]]

这是多个列表的可重用函数:

list1 = [['John',2],['Smith',5],['Kapil',3]]
list2 = [['Smith',2],['John',2],['Stephen',3]]
list3 = [['Smith',7],['John',5],['Kapil',33]]

def sort_lists(*args):
    dict = {}
    for arg in args:
        for item in arg:
            try:
                dict[item[0]] += item[1]
            except:
                dict[item[0]] = item[1]
    results = []
    for k, v in dict.items():
        results.append([k, v])

    return results

print sort_lists(list1, list2, list3)