Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – List Elements Grouping in Matrix
When working with matrices (list of lists), you sometimes need to group elements based on certain criteria. This example demonstrates how to group list elements in a matrix using iteration, the pop() method, list comprehension, and append() methods.
Example
Below is a demonstration of grouping matrix elements ?
my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
print("The list is :")
print(my_list)
check_list = [14, 12, 41, 62]
print("The check list is :")
print(check_list)
my_result = []
while my_list:
sub_list_1 = my_list.pop()
sub_list_2 = [element for element in check_list if element not in sub_list_1]
try:
my_list.remove(sub_list_2)
my_result.append([sub_list_1, sub_list_2])
except ValueError:
my_result.append(sub_list_1)
print("The result is :")
print(my_result)
The list is : [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]] The check list is : [14, 12, 41, 62] The result is : [[[41, 14], [12, 62]], [78, 87], [51, 23], [14, 62]]
How It Works
The algorithm processes the matrix by ?
-
Popping elements: Remove the last element from
my_listand assign it tosub_list_1 -
Finding complement: Create
sub_list_2containing elements fromcheck_listthat are not insub_list_1 -
Grouping logic: If
sub_list_2exists in the remaining matrix, group them together; otherwise, keepsub_list_1alone -
Exception handling: Use try-except to handle cases where
sub_list_2is not found in the matrix
Step-by-Step Breakdown
Let's trace through the execution ?
# Initial state
my_list = [[14, 62], [51, 23], [12, 62], [78, 87], [41, 14]]
check_list = [14, 12, 41, 62]
# Step 1: Pop [41, 14]
# sub_list_2 = [12, 62] (elements in check_list but not in [41, 14])
# [12, 62] exists in my_list, so group them: [[41, 14], [12, 62]]
# Step 2: Pop [78, 87]
# sub_list_2 = [14, 12, 41, 62] (none of check_list elements in [78, 87])
# [14, 12, 41, 62] doesn't exist in my_list, so keep [78, 87] alone
print("This demonstrates the grouping logic step by step")
This demonstrates the grouping logic step by step
Conclusion
This approach groups matrix elements by finding complementary sublists based on a reference list. The pop() method processes elements in reverse order, while try-except handling manages cases where no matching complement exists.
Advertisements
