Python按键拉链

jlb*_*b83 3 python list

我想组合(zip?)两个python的元组列表,但匹配一个键.

例如,我想创建一个带有两个输入列表并生成如下输出的函数:

lst1 = [(0, 1.1), (1, 1.2), (2, 1.3),           (5, 2.5)]
lst2 = [          (1, 4.5), (2, 3.4), (4, 2.3), (5, 3.2)]

desiredOutput = [(1, 1.2, 4.5), (2, 1.3, 3.4), (5, 2.5, 3.2)]
Run Code Online (Sandbox Code Playgroud)

我可以非常混乱和手动循环,但我认为必须有一些itertools/压缩功能,将大大简化这一点.

我确定答案就在那里而且显而易见,我只是没有正确的语法来搜索它.

==

((对于它的价值,这是我天真的解决方案.我希望找到更整洁/更pythonic的东西:

def key_zipper(lst1, lst2):    
    dict1 = dict(lst1)
    dict2 = dict(lst2)

    intersectKeys = [k for k in dict1.keys() if k in dict2.keys()]

    output = []

    for key in intersectKeys:
        output.append((key, dict1[key], dict2[key]))

    return output
Run Code Online (Sandbox Code Playgroud)

谢谢 ))

Vin*_*ent 11

>>> [(i, a, b) for i, a in lst1 for j, b in lst2 if i==j]
[(1, 1.2, 4.5), (2, 1.3, 3.4), (5, 2.5, 3.2)]
Run Code Online (Sandbox Code Playgroud)