하나의 하위 목록을 특정 색인에서 공통 값을 공유하는 경우 다른 하위 목록으로 확장하는 가장 효율적인 방법은 무엇입니까? List1의 인덱스 0에있는 값이 List2의 인덱스 0에있는 값과 같은 경우 두 개의 하위 목록을 병합하고 싶습니다.두 하위 목록의 동일한 색인에서 공통 ID를 공유하는 경우 하위 목록을 다른 하위 목록으로 확장하는 방법은 무엇입니까?
List1 = [['aaa','b','c'],['ddd','e','f']]
List2 = [['aaa','1','2'],['ddd','3','4']]
원하는 출력 :
[['aaa','b','c','aaa','1','2'],['ddd','e','f','ddd','3','4']]
내 해킹 :
from collections import defaultdict
Keys2 = map(lambda x: x[0], List2) #returns ['aaa','ddd']
List2_of_Tuples = zip(Keys,List2) #returns [('aaa',['aaa','1','2']),('ddd',['ddd','3','4'])]
Keys1 = map(lambda x: x[0], List1)
List1_of_Tuples = zip(Keys,List1)
Merged_List_of_Tuples = List1_of_Tuples + List2_of_Tuples
d = defaultdict(list)
for k,v in Merged_List_of_Tuples:
d[k].append(v)
Desired_Result = map(lambda x: [item for sublist in x[1] for item in sublist],d.items())
이 반환
[['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']]
내가 두 개 이상의 큰 목록에이 일을하고 있습니다. 이렇게하는 것이 더 효율적인 방법이 있습니까?
무엇 입력이 list1, list2 = [[ 'aaa', 'b', 'c'], [ 'ddd', 'e', 'f'], [ 'eee', 'g', 'h' ]], [[ 'aaa, 1, 2, ddd, 3, 4]]? – thefourtheye