添加两个列表的最佳方式?

时间:2012-02-07 14:06:40

标签: python list tuples

我有两个清单

list1 = [(100, A, 22), (200,B, 33), (300, C, 44)]

list2 = [(100,A,333), (200,B,444), (500, D, 555)]

所以我想要的最终名单是

final_list = [ (100,A, 22, 333), (200,B,33,444), (300,C,44,0), (500,D,0,555)]

如果我只是添加两个列表,它不会帮助我。我怎样才能达到最终名单。

由于

2 个答案:

答案 0 :(得分:8)

您的输入数据首先应该是字典:

dict1 = {(100, "A"): 22, (200,"B"): 33, (300, "C"): 44}
dict2 = {(100, "A"): 333, (200,"B"): 444, (500, "D"): 555}

现在您可以轻松构建组合字典:

>>> {k: (dict1.get(k, 0), dict2.get(k, 0))
...  for k in dict1.viewkeys() | dict2.viewkeys()}
{(100, 'A'): (22, 333), (200, 'B'): (33, 444), 
 (300, 'C'): (44, 0), (500, 'D'): (0, 555)}

(Python 2.7)

如果出于某种原因需要操作列表,我建议您先将列表转换为词典

dict1 = {(k1, k2): v for k1, k2, v in list1}
dict2 = {(k1, k2): v for k1, k2, v in list2}

答案 1 :(得分:1)

鉴于A,B,C,D等是不可变对象,最简单的方法是:

[list(set(x) | set(y)) for x, y in zip(list1, list2)]