[英]Merge two list of tuples with unequal length
一個如何合並兩個不相等的元組列表:
x = [('Animal', 1), ('Bird', 2)]
y = [('Animal', 'Dog'), ('Animal', 'Cat'), ('Bird', 'Parrot')]
..要得到..
[('Animal', 1, 'Dog'), ('Animal', 1, 'Cat'), ('Bird', 2, 'Parrot')]
..使用列表理解?
將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
轉換為動物字典到數字列表來再次加快速度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.