How to extend one sublist by another sublist if they share a common id at the same index in both sublists?

StackOverflow https://stackoverflow.com/questions/21346440

  •  02-10-2022
  •  | 
  •  

Pregunta

What's the most efficient way of extending one sublist with another sublist if they share a common value at a particular index? I'd like to merge two sublists together if a value at index 0 of List1 is equal to the value of index 0 of List2.

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

Desired Output:

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

My hack:

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())

This returns:

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

I'm doing this to more than two large lists. Is there a shorter more efficient way of doing this?

¿Fue útil?

Solución 2

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

Output

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

Otros consejos

I would just use list comprehension.

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]]

Result:

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

I assume that List1 doesn't necessarily have a matching item in List2?

How about:

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])])

or if you don't want to modify the list in place:

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])])
print [List1[0]+List2[0],List1[1]+list2[1]]

Here is another approach:

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top