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
# Python3 code to demonstrate working of
# List Elements Grouping in Matrix
# Using loop
# initializing list
test_list = [[4, 6], [1, 2], [2, 6], [7, 8], [1, 4]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check_list
check_list = [1, 2, 4, 6]
res = []
while test_list:
# getting row
sub1 = test_list.pop()
# getting elements not in row
sub2 = [ele for ele in check_list if ele not in sub1]
try:
# testing if we have list of removed elements
test_list.remove(sub2)
# grouping if present
res.append([sub1, sub2])
except ValueError:
# ungrouped.
res.append(sub1)
# printing result
print("The Grouped rows : " + str(res))
OutputThe 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 = []
# loop over each row in the test_list
for row in test_list:
# create a sublist to store the matching elements
match = []
# loop over each element in the row
for elem in row:
# check if the element is in the check_list
if elem in check_list:
# if it is, add it to the match list
match.append(elem)
else:
# if it's not, break out of the loop and move on to the next row
break
else:
# if all elements in the row are in the check_list, append the row to the result
res.append(row)
continue
# if we get to this point, some elements in the row are not in the check_list,
# so we need to create a sublist to store those elements
non_match = []
for elem in row:
if elem not in match:
non_match.append(elem)
# append both the match and non_match sublists to the result
res.append([match, non_match])
print("The Grouped rows : " + str(res))
OutputThe 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]
# initialize a dictionary with keys from check_list and empty lists as values
grouped_dict = {key: [] for key in check_list}
# iterate through each sublist in test_list
for sublist in test_list:
# iterate through each element in the sublist
for element in sublist:
# check if the element is in the check_list
if element in check_list:
# append the sublist to the corresponding key in the dictionary
grouped_dict[element].append(sublist)
# convert the dictionary to a list of sublists
grouped_list = [[grouped_dict[key], [key]] for key in check_list]
# print the result
print("The Grouped rows : " + str(grouped_list))
OutputThe 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 = []
# iterate through each value in check_list
for val in check_list:
# create an empty list to store the sublists that contain the current value
sublists = []
# iterate through each sublist in test_list
for sublist in test_list:
# check if the current value is in the sublist
if val in sublist:
# append the sublist to the list of sublists
sublists.append(sublist)
# append the list of sublists and the current value to grouped_list
grouped_list.append([sublists, [val]])
# print the result
print("The Grouped rows : " + str(grouped_list))
OutputThe 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))
OutputThe 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))
OutputThe 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
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
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 | Frequency grouping of list elements
Sometimes, while working with lists, we can have a problem in which we need to group element along with it's frequency in form of list of tuple. Let's discuss certain ways in which this task can be performed. Method #1: Using loop This is a brute force method to perform this particular task. In this
6 min read
Python - Elements frequency in Tuple Matrix
Sometimes, while working with Python Tuple Matrix, we can have a problem in which we need to get the frequency of each element in it. This kind of problem can occur in domains such as day-day programming and web development domains. Let's discuss certain ways in which this problem can be solved. Inp
5 min read
Python - Elements Lengths in List
Sometimes, while working with Python lists, can have problem in which we need to count the sizes of elements that are part of lists. This is because list can allow different element types to be its members. This kind of problem can have application in many domains such has day-day programming and we
6 min read