简体   繁体   English

如何在python中压缩两个元组列表

[英]how to zip two lists of tuples in python

I have two lists of tuples, for example: 我有两个元组列表,例如:

a = [(1,2,3),(4,5,6),(7,8,9)]
b = [(1,'a'),(4,'b'),(7,'c')]

The first element of each tuple in a and b are matched, I want to get a list like this: a和b中每个元组的第一个元素是匹配的,我想得到一个这样的列表:

merged = [(1,2,3,'a'),(4,5,6,'b'),(7,8,9,'c')]

Perhaps I will have another list like: 也许我会有另一个列表,如:

c = [(1,'xx'),(4,'yy'),(7,'zz')]

and merge it to "merged" list later, I tried "zip" and "map" which are not right for this case. 并在以后合并到“合并”列表,我尝试了“zip”和“map”,这不适合这种情况。

>>> a = [(1,2,3),(4,5,6),(7,8,9)]
>>> b = [(1,'a'),(4,'b'),(7,'c')]
>>> 
>>> [x + (z,) for x, (y, z) in zip(a, b)]
[(1, 2, 3, 'a'), (4, 5, 6, 'b'), (7, 8, 9, 'c')]

to check if first elements actually match, 检查第一个元素是否实际匹配,

>>> [x + y[1:] for x, y in zip(a, b) if x[0] == y[0]]
def merge(a,b):
    for ax, (first, bx) in zip(a,b):
        if ax[0] != first:
            raise ValueError("Items don't match")
        yield ax + (bx,)

print list(merge(a,b))
print list(merge(merge(a,b),c))
>>> [a[i]+(k,) for i,(j, k) in enumerate(b)]
[(1, 2, 3, 'a'), (4, 5, 6, 'b'), (7, 8, 9, 'c')]

Using timeit this is the fastest of the posted solutions to return a merged list. 使用timeit这是返回合并列表的最快发布解决方案。

[ (x,y,z,b[i][1]) for i,(x,y,z) in enumerate(a) if x == b[i][0] ]

这可确保匹配然后合并值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM