2014-01-25 2 views
0

하나의 하위 목록을 특정 색인에서 공통 값을 공유하는 경우 다른 하위 목록으로 확장하는 가장 효율적인 방법은 무엇입니까? 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']] 

내가 두 개 이상의 큰 목록에이 일을하고 있습니다. 이렇게하는 것이 더 효율적인 방법이 있습니까?

+0

무엇 입력이 list1, list2 = [[ 'aaa', 'b', 'c'], [ 'ddd', 'e', ​​'f'], [ 'eee', 'g', 'h' ]], [[ 'aaa, 1, 2, ddd, 3, 4]]? – thefourtheye

답변

1
list1,list2 = [['aaa','b','c'],['ddd','e','f']],[['aaa','1','2'],['ddd','3','4']] 

from itertools import chain, groupby 
from operator import itemgetter 
get_first, result = itemgetter(0), [] 
for key, grp in groupby(sorted(chain(list1, list2), key = get_first), get_first): 
    result.append([item for items in grp for item in items]) 
print result 

출력

[['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']] 
+0

itertools를 사용하기 때문에이 답변을 정말 좋아합니다. 이는 속도와 효율성을 의미합니다. 내가 그것과 함께 실행중인 한 가지 문제는 일치 목록이 두 목록에서 동일하지 않은 위치에 적용하고 싶습니다. 하위 목록에 일치하는 문자열이 동일한 위치에있는 경우 (일치하는 인덱스보다 위에있는 경우)에만 적용 할 수 있지만 목록 1에서 일치하는 인덱스가 위와 같이 0 인 경우 목록 2에서 일치하는 인덱스는 2시에? (예 : list1, list2 = [[ 'aaa', 'b', 'c'], [ 'ddd', 'e', ​​'f']], [[ '1', '2', 'aaa'] , [ '3', '4', 'ddd']])). 이것이 가능한가? – Chris

+0

@Chris 그러나 그것은 원래 질문의 일부가 아니 었습니다. ( – thefourtheye

+0

당신은 완전히 옳았어요! 내 문제는 여전히 풀었지만 새로운 문제가 생겨서, 같은 방법론을 적용 할 수 있을지 궁금 해서요. 위의 해결책 중 하나를이 새로운 문제에 사용할 수는 있지만 (빠른 것은 아니지만) 원본 도전에 이미 사용하고 있습니다. 감사합니다. – Chris

2

나는 단지 목록 이해력을 사용합니다.

List1 = [['aaa','b','c'],['ddd','e','f']] 
List2 = [['aaa','1','2'],['ddd','3','4']] 

new_list = [a + b for a, b in zip(List1, List2) if a[0] == b[0]] 

결과 :

>>> new_list 
[['aaa', 'b', 'c', 'aaa', '1', '2'], ['ddd', 'e', 'f', 'ddd', '3', '4']] 
+0

'특정 인덱스에서 공통 값을 공유하는 경우'를 놓쳤습니다. – Gerrat

+0

@Gerrat, Fixed. 감사. – Akavall

0

나는 List1 반드시 List2에 일치하는 항목이없는 가정?

방법에 대해 : 당신이 장소에서 목록을 수정하지 않으려는 경우 또는

list2_keys = map(lambda x:x[0],List2) 
for i,l in enumerate(List1): 
    if l[0] in list2_keys: 
     List1[i].extend(List2[list2_keys.index(l[0])]) 

:

list2_keys = map(lambda x:x[0],List2) 
new_list = [] 
for i,l in enumerate(List1): 
    if l[0] in list2_keys: 
     new_list.append(List1[i]+List2[list2_keys.index(l[0])]) 
여기
+0

사실, 나는'map'의 성능에 대해 확신하지 못합니다. list2_keys = [l [0] for List2]'를 통해'list2_keys'를 생성 해 볼 수 있습니다. –

0
print [List1[0]+List2[0],List1[1]+list2[1]] 
0

다른 접근 방식입니다 :

List1 = [['aaa','b','c'],['ddd','e','f'],['a','b'],['k','l']] 
List2 = [['aaa','1','2'],['ddd','3','4'],['c','d']] 
new_list = [] 

for (index, elem) in enumerate(List1): 
    try: 
     if elem[0] == List2[index][0]: 
      new_list.append(elem+List2[index]) 
    except IndexError: 
     break 

print new_list