首页 > 解决方案 > 合并两个长度不等的元组列表

问题描述

如何合并两个不相等的元组列表:

x = [('Animal', 1), ('Bird', 2)]
y = [('Animal', 'Dog'), ('Animal', 'Cat'), ('Bird', 'Parrot')]

..要得到..

[('Animal', 1, 'Dog'), ('Animal', 1, 'Cat'), ('Bird', 2, 'Parrot')]

..使用列表理解?

标签: pythonpython-3.x

解决方案


变成x字典方便查找,然后...

xx = dict(x)
[(k, xx[k], a) for k, a in y]
# => [('Animal', 1, 'Dog'), ('Animal', 1, 'Cat'), ('Bird', 2, 'Parrot')]

编辑:现在这是一个完全不同的问题。

[(k, n, a) for k, a in y for kk, n in x if kk == k]
# => [('Animal', 1, 'Dog'), ('Animal', 2, 'Dog'), ('Animal', 1, 'Cat'),
#     ('Animal', 2, 'Cat'), ('Bird', 2, 'Parrot')]

x您可以通过将动物字典转换为数字列表来再次加快速度。


推荐阅读