什么是合并2个元组列表并在元组中添加非唯一值的Pythonic方法是什么?

时间:2011-09-25 06:11:23

标签: list python

我正在寻找重构下面Python代码的最佳方法。我认为在2或3行代码中有一种Pythonic方法可以做到这一点,但无法弄明白。我搜索过Stackoverflow但找不到类似的问题和解决方案。非常感谢!

list1 = [(Python, 5), (Ruby, 10), (Java, 15), (C++, 20)]
list2 = [(Python, 1), (Ruby, 2), (Java, 3), (PHP, 4), (Javascript, 5)]

# I want to make an unsorted list3 like this
# list3 = [(Python, 6), (Ruby, 12), (Java, 18), (PHP, 4), (Javasript, 5), (C++, 20)]
common_keys = list(set(dict(list1).keys()) & set(dict(list2).keys()))

if common_keys:
    common_lst = [(x, (dict(list1)[x] + dict(list2)[x])) for x in common_keys]
    rest_list1 = [(x, dict(list1)[x]) for x in dict(list1).keys() if x not in common_keys]
    rest_list2 = [(x, dict(list2)[x]) for x in dict(list2).keys() if x not in common_keys]
    list3 = common_lst + rest_list1 + rest_list2

else:
    list3 = list1 + list2

1 个答案:

答案 0 :(得分:5)

您正在寻找collections.defaultdict

from collections import defaultdict
from itertools import chain

merged = defaultdict(int)

for key, value in chain(list1, list2):
    merged[key] += value

如果您需要list tuple s:

list3 = merged.items()

如果你想在没有chain的情况下这样做,你可以这样做:

from collections import defaultdict

merged = defaultdict(int)

merged.update(list1)

for key, value in list2:
    merged[key] += value

编辑:正如Beni在评论中指出的那样,在2.7 / 3.2 +上,您可以这样做:

from collections import Counter

merged = Counter(dict(list1))
merged.update(dict(list2))

这要求您将列表转换为dict,但其他方面则完美无缺。