Python – List Elements Grouping in Matrix
Last Updated :
31 Mar, 2023
Given a Matrix, for groups according to list elements, i.e each group should contain all elements from List.
Input : test_list = [[2, 6], [7, 8], [1, 4]], check_list = [1, 2, 4, 6]
Output : [[7, 8], [[1, 2], [4, 6]]]
Explanation : 1, 2, 4, 6 elements rows are grouped.
Input : test_list = [[2, 7], [7, 8], [1, 4]], check_list = [1, 2, 4, 6]
Output : [[2, 7], [7, 8], [1, 4]]
Explanation : No grouping possible.
Method : Using loop + list comprehension + Try-Except
In this, for each row in matrix, get elements missing from list, after getting elements, match with each row if we can find missing elements if found, the new group is made.
Python3
test_list = [[ 4 , 6 ], [ 1 , 2 ], [ 2 , 6 ], [ 7 , 8 ], [ 1 , 4 ]]
print ( "The original list is : " + str (test_list))
check_list = [ 1 , 2 , 4 , 6 ]
res = []
while test_list:
sub1 = test_list.pop()
sub2 = [ele for ele in check_list if ele not in sub1]
try :
test_list.remove(sub2)
res.append([sub1, sub2])
except ValueError:
res.append(sub1)
print ( "The Grouped rows : " + str (res))
|
Output
The original list is : [[4, 6], [1, 2], [2, 6], [7, 8], [1, 4]]
The Grouped rows : [[[1, 4], [2, 6]], [7, 8], [[1, 2], [4, 6]]]
Time complexity: O(n^2), where n is the length of the input list test_list
Auxiliary space: O(n), where n is the length of the input list test_list.
Method 2: Looping over nested Loops in Python
- Each row in the test_list
- Here for each row, it creates a sublist called match to store the elements in the row that are in the check_list.
- It then loops over each element in the row, and if it finds an element that is not in the check_list, it breaks out of the loop and moves on to the next row.
Python3
test_list = [[ 4 , 6 ], [ 1 , 2 ], [ 2 , 6 ], [ 7 , 8 ], [ 1 , 4 ]]
check_list = [ 1 , 2 , 4 , 6 ]
res = []
for row in test_list:
match = []
for elem in row:
if elem in check_list:
match.append(elem)
else :
break
else :
res.append(row)
continue
non_match = []
for elem in row:
if elem not in match:
non_match.append(elem)
res.append([match, non_match])
print ( "The Grouped rows : " + str (res))
|
Output
The Grouped rows : [[4, 6], [1, 2], [2, 6], [[], [7, 8]], [1, 4]]
Time complexity: O(n*m), where n is the number of rows in the test_list and m is the maximum number of elements in any row.
Auxiliary space: O(n*m), because we create a new list to store the result, and for each row that has elements that are not in the check_list, we create two new sublists to store the matching and non-matching elements.
Method 3: Using dictionary
You can use a dictionary to group the elements in the given list based on their value. Here’s how you can do it:
Python3
test_list = [[ 4 , 6 ], [ 1 , 2 ], [ 2 , 6 ], [ 7 , 8 ], [ 1 , 4 ]]
check_list = [ 1 , 2 , 4 , 6 ]
grouped_dict = {key: [] for key in check_list}
for sublist in test_list:
for element in sublist:
if element in check_list:
grouped_dict[element].append(sublist)
grouped_list = [[grouped_dict[key], [key]] for key in check_list]
print ( "The Grouped rows : " + str (grouped_list))
|
Output
The Grouped rows : [[[[1, 2], [1, 4]], [1]], [[[1, 2], [2, 6]], [2]], [[[4, 6], [1, 4]], [4]], [[[4, 6], [2, 6]], [6]]]
Time complexity: O(nm), where n is the length of the test_list and m is the length of the check_list.
Auxiliary space: O(m + k), where m is the length of the check_list and k is the number of unique elements in test_list that are in check_list.
Method 4: Using set intersection
We can use set intersection to filter the test_list by the values in check_list and group them accordingly.
Approach:
- Define test_list as a list of lists, where each sublist contains two integers.
- Define check_list as a list of integers.
- Create an empty list grouped_list to store the result.
- Iterate through each value val in check_list.
- Create an empty list sublists to store the sublists in test_list that contain the current value val.
- Iterate through each sublist sublist in test_list.
- Check if the current value val is in the sublist sublist.
- If val is in sublist, append sublist to sublists.
- Append sublists and val as a list to grouped_list.
- Print the resulting list of lists.
Python3
test_list = [[ 4 , 6 ], [ 1 , 2 ], [ 2 , 6 ], [ 7 , 8 ], [ 1 , 4 ]]
check_list = [ 1 , 2 , 4 , 6 ]
grouped_list = []
for val in check_list:
sublists = []
for sublist in test_list:
if val in sublist:
sublists.append(sublist)
grouped_list.append([sublists, [val]])
print ( "The Grouped rows : " + str (grouped_list))
|
Output
The Grouped rows : [[[[1, 2], [1, 4]], [1]], [[[1, 2], [2, 6]], [2]], [[[4, 6], [1, 4]], [4]], [[[4, 6], [2, 6]], [6]]]
Time complexity: O(n*m), where n is the length of check_list and m is the length of the longest sublist in test_list.
Auxiliary space: O(nm), where n is the length of check_list and m is the length of the longest sublist in test_list.
Method 5: Using a nested loop and a flag variable to keep track of grouped elements
This method iterates through each row in the list and then iterates through each element in the row. If an element is in the check_list, it is added to a grouped_row list. If an element is not in the check_list, it is added to an ungrouped_row list. At the end of the iteration through each element, if there are any ungrouped elements, they are added to the grouped_list. If there are any grouped elements, they are also added to the grouped_list. This method uses a flag variable to keep track of whether any grouped elements or ungrouped elements were found in the current row.
Python3
test_list = [[ 4 , 6 ], [ 1 , 2 ], [ 2 , 6 ], [ 7 , 8 ], [ 1 , 4 ]]
check_list = [ 1 , 2 , 4 , 6 ]
grouped_list = []
for row in test_list:
grouped_row = []
ungrouped_row = []
for elem in row:
if elem in check_list:
grouped_row.append(elem)
else :
ungrouped_row.append(elem)
if ungrouped_row:
grouped_list.append(ungrouped_row)
if grouped_row:
grouped_list.append(grouped_row)
print ( "The Grouped rows : " + str (grouped_list))
|
Output
The Grouped rows : [[4, 6], [1, 2], [2, 6], [7, 8], [1, 4]]
Time complexity: O(n^2), where n is the total number of elements in the test_list.
Auxiliary space: O(n^2), since we are creating new lists for each grouped and ungrouped row, and appending these lists to the grouped_list.
Method 6: Using the built-in function filter() along with lambda function.
Step-by-step approach:
- Define the test_list and check_list:
- Use the filter() function with a lambda function to select the elements in each row that are in the check_list:
- Combine the grouped and ungrouped elements for each row into a single list using a list comprehension:
- Print the grouped_list
Below is the implementation of the above approach:
Python3
test_list = [[ 4 , 6 ], [ 1 , 2 ], [ 2 , 6 ], [ 7 , 8 ], [ 1 , 4 ]]
check_list = [ 1 , 2 , 4 , 6 ]
grouped_rows = list ( map ( lambda row: list ( filter ( lambda x: x in check_list, row)), test_list))
ungrouped_rows = list ( map ( lambda row: list ( filter ( lambda x: x not in check_list, row)), test_list))
grouped_list = [row for row in grouped_rows + ungrouped_rows if row]
print ( "The Grouped rows : " + str (grouped_list))
|
Output
The Grouped rows : [[4, 6], [1, 2], [2, 6], [1, 4], [7, 8]]
Time complexity: O(n^2), where n is the number of rows in the test_list.
Auxiliary space: O(n^2), because two separate lists (grouped_rows and ungrouped_rows) are created to hold the filtered elements for each row in the test_list.
Similar Reads
Python - Group Elements in Matrix
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
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,
8 min read
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. Met
6 min read
Python - Inter Matrix Grouping
Given 2 Matrix, with 2 elements in each row, group them on basis on first element. Input : test_list1 = [[2, 0], [8, 4], [9, 3]], test_list2 = [[8, 1], [9, 7], [2, 10]] Output : {2: [0, 10], 8: [4, 1], 9: [3, 7]} Explanation : All values after mapping cross Matrix, 2 mapped to 0 and 10. Input : test
4 min read
Python - Paired elements grouping
Sometimes, while working with Python records, we can have a problem in which we have tuple list as data and we desire to group all the elements which form a chain, i.e are indirect pairs of each other or are connected components. This kind of problem can occur in domains such as competitive programm
6 min read
Group Elements at Same Indices in a Multi-List - Python
We are given a 2D list, we have to group elements at the same indices in a multi-list which means combining elements that are positioned at identical indices across different list. For example:If we have a 2D list: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] then grouping elements at the same indices would re
4 min read
Python | Binary element list grouping
Sometimes while working with the databases, we need to perform certain list operations that are more like query language, for instance, grouping of nested list element with respect to its other index elements. This article deals with binary nested list and group each nested list element with respect
9 min read
Search Elements in a Matrix - Python
The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
3 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 meth
4 min read
Python - Similar index elements Matrix
Sometimes, while working with data, we can have a problem in which we need to perform the construction of matrix from lists element vertically than horizontally. This kind of application can come in Data Science domains in which we need to construct Matrix from several lists. Lets discuss certain wa
7 min read