Python - Merge two List of Lists According to First Element


Introduction

Python is a flexible and effective programming dialect broadly utilized for different assignments, counting information control and examination. When it comes to blending two records of records based on their to begin with component, Python gives a productive and exquisite solution. To combine these records, you'll utilize the built−in sorted() function with a custom sorting key. The key will be characterized as the primary component of each sublist. By sorting both records based on this key, you ensure that the sublists with coordinating to begin with components are adjoining to each other.

Merge two List of Lists According to First Element

Simplicity and Lucidness: Python is known for its effortlessness and lucidness. The code to combine two records of records based on the primary component can be composed concisely and clearly. This makes it simpler to get it and keep up the code, indeed for designers who are unused to Python.

Built−in Capacities and Libraries: Python gives built−in capacities and libraries that rearrange the consolidating handle. Capacities like sorted(), itertools.groupby(), and list comprehension permit for proficient consolidating based on custom sorting keys or gathering criteria. These built−in apparatuses spare time and exertion in actualizing the consolidating rationale from scratch.

Adaptability and Customization: Python offers adaptability in executing the combining handle concurring to particular prerequisites.

Approach 1: Sorting and Merging

Algorithm

Step 1 :Combine the two records into a single list.

Step 2 :Combine the two records into a single list.

Step 3 :Initialize a purge list to store the blended sublists.

Step 4 :Repeat through the sorted list.

Step 5 :Compare the current sublist's, to begin with the component with the past sublist's, to begin with the component.

Step 6 :In case they coordinate, blend the sublists and overhaul the combined list.

Step 7 :In case they do not coordinate, add the current sublist to the consolidated list.

Step 8 :Return the blended list.

Example

def merge_lists(list1, list2):
    combined_list = list1 + list2
    sorted_list = sorted(combined_list, key=lambda x: x[0])
    merged_list = [sorted_list[0]]
    
    for sublist in sorted_list[1:]:
        if sublist[0] == merged_list[-1][0]:
            merged_list[-1].extend(sublist[1:])
        else:
            merged_list.append(sublist)
    
    return merged_list


list1 = [[1, 'g'], [3, 'x'], [5, 'e']]
list2 = [[2, 'j'], [4, 'y'], [6, 'u']]

merged = merge_lists(list1, list2)
print(merged)

Output

[[1, 'g'], [2, 'j'], [3, 'x'], [4, 'y'], [5, 'e'], [6, 'u']]

Approach 2: Using a Dictionary

Algorithm

Step 1 :Combine the two records into a single list.

Step 2 :Initialize a purge word reference.

Step 3 :Emphasize through the combined list.

Step 4 :Extricate the primary component of each sublist and check in the event that it exists as a key within the word reference.

Step 5 :In the event that the key exists, amplify the comparing esteem with the remaining components of the sublist.

Step 6 :If the key doesn't exist, include it in the lexicon with the remaining components of the sublist as its esteem.

Step 7 :Return a list of sublists by changing over the lexicon things.

Example

def merge_lists(list1, list2):
    combined_list = list1 + list2
    merged_dict = {}
    
    for sublist in combined_list:
        key = sublist[0]
        value = sublist[1:]
        
        if key in merged_dict:
            merged_dict[key].extend(value)
        else:
            merged_dict[key] = value
    
    merged_list = [[key] + value for key, value in merged_dict.items()]
    
    return merged_list


list1 = [[1, 'v'], [3, 'c'], [5, 'l']]
list2 = [[2, 'z'], [4, 'y'], [6, 'd']]

merged = merge_lists(list1, list2)
print(merged)

Output

[[1, 'v'], [3, 'c'], [5, 'l'], [2, 'z'], [4, 'y'], [6, 'd']]

Approach 3: Using itertools.groupby

Algorithm

Step 1 :Creation of a function and combining the two records into a single list.

Step 2 :Sort the combined list based on the primary component of each sublist.

Step 3 :Utilize itertools.groupby to bunch the sorted list by the primary component.

Step 4 :Initialize a purge list to store the combined sublists.

Step 5 :Repeat through the assembled components.

Step 6 :Extricate the key (to begin with component) and values (remaining components) from each gathering.

Step 7 :Combine the values of each gather into a single sublist.

Step 8 :Add the consolidated sublist to the result list.

Step 9 :Return the resulting list.

Example

import itertools

def merge_lists(list1, list2):
    combined_list = list1 + list2
    sorted_list = sorted(combined_list, key=lambda x: x[0])
    grouped = itertools.groupby(sorted_list, key=lambda x: x[0])
    
    merged_list = []
    for key, group in grouped:
        values = list(itertools.chain.from_iterable([x[1:] for x in group]))
        merged_list.append([key] + values)
    
    return merged_list


list1 = [[1, 'f'], [3, 'w'], [5, 'e']]
list2 = [[2, 'r'], [4, 'q'], [6, 's']]

merged = merge_lists(list1, list2)
print(merged)

Output

[[1, 'f'], [2, 'r'], [3, 'w'], [4, 'q'], [5, 'e'], [6, 's']]

Conclusion

Merging two records of records based on the primary component could be a common operation in Python. In this article, we investigated three distinctive approaches to realize this errand. We examined the calculations, gave step−by−step clarifications, and displayed the comparing Python code and yields for each approach.

By using sorting and blending, word references, or itertools.group by, we will proficiently consolidate these records while keeping up the required arrangement. Depending on the estimate and complexity of the information, you'll be able to select the foremost appropriate approach for your particular utilize case. Python's adaptability and broad libraries make it an effective device for information control errands like consolidating records.

Updated on: 07-Aug-2023

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements