I have two lists of two elements tuples. First element of tuple is ID and second is some kind of value. 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:
lst3 = [(k, v, dict2[k]) for k, v in lst1]
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다