Python - Merge a Matrix by the Elements of First Column

PythonServer Side ProgrammingProgramming

When it is required to merge a matrix by the elements of first column, a simple iteration and list comprehension and ‘setdefault’ method is used.

Example

Below is a demonstration of the same −

my_list = [[41, "python"], [13, "pyt"], [41, "is"],[4, "always"], [3, "fun"]]

print("The list is :")
print(my_list)

my_result = {}
for key, value in my_list:

   my_result.setdefault(key, []).append(value)

my_result = [[key] + value for key, value in my_result.items()]

print("The result is :")
print(my_result)

Output

The list is :
[[41, 'python'], [13, 'pyt'], [41, 'is'], [4, 'always'], [3, 'fun']]
The result is :
[[41, 'python', 'is'], [13, 'pyt'], [4, 'always'], [3, 'fun']]

Explanation

  • A list is defined and displayed on the console.

  • An empty dictionary is created.

  • The list is iterated over, and the key-value pair with same keys are joined together and appended to the dictionary.

  • A list comprehension is used to get the elements of the dictionary, and the key and the value are added.

  • This is assigned to a variable.

  • This is the output that is displayed on the console.

raja
Updated on 08-Sep-2021 09:20:12

Advertisements