Open In App

Python – Group Elements in Matrix

Last Updated : 10 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Matrix with two columns, group 2nd column elements on basis of 1st column.

Input : test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [2, 9]] 
Output : {5: [8, 4], 2: [0, 3, 9]} 
Explanation : 8 and 4 are mapped to 5 in Matrix, all others to 2. 

Input : test_list = [[2, 8], [2, 0], [2, 4], [2, 3], [2, 9]] 
Output : {2: [8, 4, 0, 3, 9]} 
Explanation : All mapped to 2.

Method #1 : Using dictionary comprehension + loop

This is one of the ways in which this task can be performed. In this, we construct the dictionary with empty list values from row 1 and then run a loop to assign values into it.

Step-by-step approach:

  • Initialize the list of lists as the input list.
  • Print the original list.
  • Initialize an empty dictionary with default empty lists using dictionary comprehension. The keys are the first elements of the tuples in the input list.
  • Loop through the input list and append the second element of each tuple to the list in the dictionary with the same key.
  • Print the result, which is the dictionary with the grouped elements.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Group Elements in Matrix
# Using dictionary comprehension + loop
 
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing empty dictionary with default empty list
res = {idx[0]: [] for idx in test_list}
 
# using loop for grouping
for idx in test_list:
    res[idx[0]].append(idx[1])
 
# printing result
print("The Grouped Matrix : " + str(res))


Output

The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), as a dictionary is created with n key-value pairs.

Method #2 : Using loop + defaultdict()

This is similar to above method. The difference being that initial empty mesh is created using defaultdict().

Python3




# Python3 code to demonstrate working of
# Group Elements in Matrix
# Using loop + defaultdict()
from collections import defaultdict
 
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing empty dictionary using defaultdict
res = defaultdict(list)
 
# using loop for grouping
for idx in test_list:
    res[idx[0]].append(idx[1])
 
# printing result
print("The Grouped Matrix : " + str(dict(res)))


Output

The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}

The time complexity of this code is O(n), where n is the number of elements in the input list. 

The auxiliary space complexity of this code is also O(n), where n is the number of elements in the input list.

Method #3 : Using nested for loops

Approach 

  1. Extracting the unique 0 index values from nested list
  2. Initiated a nested for loop to group similar first index elements

Python3




# Python3 code to demonstrate working of
# Group Elements in Matrix
# Using dictionary comprehension + loop
 
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# initializing empty dictionary with default empty list
res=dict()
x=[]
for i in test_list:
    if i[0] not in x:
        x.append(i[0])
for i in x:
    v=[]
    for j in test_list:
        if j[0]==i:
            v.append(j[1])
    res[i]=v
# printing result
print("The Grouped Matrix : " + str(res))


Output

The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {5: [8, 4], 2: [0, 3], 7: [9]}

Time Complexity : O(n*n)
Auxiliary Space : O(n)

Method #4: Using itertools.groupby()

Use the itertools.groupby() function to group elements in the matrix based on their first value. This function takes an iterable and a key function as arguments, and returns an iterator that produces pairs of keys and groups of items that have the same key.

Python3




from itertools import groupby
 
# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# grouping elements based on first value
test_list.sort()
groups = groupby(test_list, lambda x: x[0])
 
# creating dictionary from groups
res = {k: [v[1] for v in group] for k, group in groups}
 
# printing result
print("The Grouped Matrix : " + str(res))


Output

The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {2: [0, 3], 5: [4, 8], 7: [9]}

Time complexity: O(n log n) due to the use of the groupby() function, which requires the input to be sorted. 
Auxiliary space: O(n), since we need to store the groups in a dictionary.

Method #5: Using list comprehension and set

This method uses list comprehension and set to group the elements in the matrix. The set function is used to get the unique elements of the first column of the matrix. Then, a dictionary comprehension is used to create a dictionary with the unique elements as keys and a list of the corresponding second column elements as values.

Python3




# initializing list
test_list = [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension and set to group elements
res = {i: [j[1] for j in test_list if j[0] == i] for i in set([k[0] for k in test_list])}
 
# printing result
print("The Grouped Matrix : " + str(res))


Output

The original list : [[5, 8], [2, 0], [5, 4], [2, 3], [7, 9]]
The Grouped Matrix : {2: [0, 3], 5: [8, 4], 7: [9]}

Time complexity: O(n^2), where n is the number of elements in the input list. 
Auxiliary space: O(n^2), as the resulting dictionary contains a key-value pair for each unique element in the first column of the input list. 



Previous Article
Next Article

Similar Reads

Python - Group elements from Dual List Matrix
Sometimes, while working with Python list, we can have a problem in which we need to group the elements in list with the first element of Matrix and perform the Grouping in form of dictionary. This can have advantage in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop + list comprehension The combi
6 min read
Python - Group similar elements into Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are the same. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 4, 4, 2, 3] Output : [[1], [2], [3, 3], [4, 4]] Input :
8 min read
Python - Group first elements by second elements in Tuple list
Given List of tuples, group 1st elements on basis of 2nd elements. Input : test_list = [(6, 5), (2, 7), (2, 5), (8, 7), (3, 7)] Output : {5: [6, 2], 7: [2, 8, 3]} Explanation : 5 occurs along with 6 and 2 in tuple list, hence grouping. Input : test_list = [(6, 5), (2, 7), (2, 5), (8, 7)] Output : {5: [6, 2], 7: [2, 8]} Explanation : 5 occurs along
5 min read
Python | Group elements at same indices in a multi-list
Flattening a 2D list to one is a common problem that is faced in many domains. But sometimes we require to pair elements at specific indices as one, so that elements at respective indices are together. This problem is not common but still having a solution to it helps. Let's discuss certain ways to pair elements at specific indices. Method #1 : Usi
9 min read
Python | Group list elements based on frequency
Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple. Examples: Input : [1, 3, 4, 4, 1, 5, 3, 1] Output : [(1, 3), (3, 2), (4, 2), (5, 1)] Input : ['x', 'a', 'x', 'y', 'a', 'x'] Output : [('x', 3), ('a', 2), ('y', 1)] Method #1: List comprehension We can use list comprehension to form
5 min read
Python | Group consecutive list elements with tolerance
Sometimes, we might need to group list according to the consecutive elements in the list. But a useful variation of this can also be a case in which we need to consider a tolerance level, i.e allowing a skip value between numbers and not being exactly consecutive but a "gap" is allowed between numbers. Let's discuss an approach in which this task c
3 min read
Python | Group elements on break positions in list
Many times we have problems involving and revolving around Python grouping. Sometimes, we might have a specific problem in which we require to split and group N element list on missing elements. Let's discuss a way in which this task can be performed. Method : Using itemgetter() + map() + lambda() + groupby() This task can be performed using the co
2 min read
Python | Binary Group Tuple list elements
Sometimes, while working with tuples, we can have problems of grouping them, be it based on gender or any particular binary category. This can have applications in many domains. Let's discuss certain ways in which this can be performed. Method #1 : Using generator + loop + zip() The brute force method to perform this task, in this, we perform the c
4 min read
Python - Group Records on Similar index elements
Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of particular index of tuple, on basis of similarity of rest of indices. This type of problems can have possible applications in Web development domain. Let's discuss certain ways in which this task can be performed. Input : test_list = [(4, 5,
6 min read
Python - Group Consecutive elements by Sign
Given a list group of consecutive elements on the basis of signs. Input : test_list = [5, -3, 2, 4, 6, -2, -1, -7, -9, 2, 3] Output : [[5], [-3], [2, 4, 6], [-2, -1, -7, -9], [2, 3]] Explanation : Elements inserted into new list on sign change.Input : test_list = [-2,3,4,5,6,-3] Output : [[-2], [3, 4, 5, 6], [-3]] Explanation : Elements inserted in
3 min read
three90RightbarBannerImg