简体   繁体   English

通过键合并两个元组列表

[英]Combine two lists of tuples by key

I have two lists of two elements tuples. 我有两个元素元组的两个列表。 First element of tuple is ID and second is some kind of value. 元组的第一个元素是ID,第二个是某种值。 Type of value depends on list. 值的类型取决于列表。

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 

What is the easiest way to combine them into: 将它们组合为最简单的方法是:

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

I suggest you turn those lists of tuples into dictionaries first. 我建议您首先将这些元组列表转换成字典。 Then, assuming that both lists contain the same "keys", you can use a simple list comprehension to get the respective values from the two dictionaries. 然后,假设两个列表都包含相同的“键”,则可以使用简单的列表推导从两个字典中获取相应的值。

lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 
dict1 = dict(lst1)
dict2 = dict(lst2)
lst3 = [(k, dict1[k], dict2[k]) for k in sorted(dict1)]

Note that dictionaries have no fixed order. 请注意,字典没有固定的顺序。 If you want to preserve the order the keys had in lst1 , you might also use this, as suggested in comments: 如果要保留键在lst1中的lst1 ,也可以使用它,如注释中所建议:

lst3 = [(k, v, dict2[k]) for k, v in lst1]
lst1 = [ ('a', 1), ('b', 2), ('c', 3) ]
lst2 = [ ('b', 5), ('a', 4), ('c', 6) ] 

dst1 = dict(lst1)
dst2 = dict(lst2)

for i in dst1:
    if i in dst2:
        dst1[i] = (dst1[i],dst2[i])

print dst1
{'a': (1, 4), 'c': (3, 6), 'b': (2, 5)}

Then you can this format dst1 to whatever format you want the result in. 然后,您可以将此dst1格式dst1为所需结果的格式。

You just need to create one dict using the first element from each tuple from lst1 as the key and storing the tuple as the value, then iterate over the second list and add the last element to the corresponding tuple in the dict. 您只需要使用lst1中每个元组中的第一个元素作为键并存储该元组作为值来创建一个dict,然后遍历第二个列表并将最后一个元素添加到dict中的相应元组即可。

lst1 = [('a', 1), ('b', 2), ('c', 3)]
lst2 = [('b', 5), ('a', 4), ('c', 6)]
from collections import OrderedDict
d = OrderedDict(zip((tup[0] for tup in lst1), lst1))

for k,v  in lst2:
    d[k] = d[k] + (v,)
print(d.values())
[('a', 1, 4), ('b', 2, 5), ('c', 3, 6)]

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

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