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
Python – Sort row by K multiples
When sorting rows based on the count of multiples of K, we can use a custom key function with list comprehension and the modulus operator. This approach counts how many elements in each row are divisible by K and sorts accordingly.
Example
Let's sort a list of sublists based on how many multiples of K each sublist contains ?
def multiple_sort_val(row):
return len([ele for ele in row if ele % K == 0])
my_list = [[11, 44, 7, 11], [7, 5, 44, 11], [11, 6, 35, 44], [92, 92, 5]]
print("The list is:")
print(my_list)
K = 11
print("The value for K is:")
print(K)
my_list.sort(key=multiple_sort_val)
print("The resultant list is:")
print(my_list)
The list is: [[11, 44, 7, 11], [7, 5, 44, 11], [11, 6, 35, 44], [92, 92, 5]] The value for K is: 11 The resultant list is: [[92, 92, 5], [7, 5, 44, 11], [11, 6, 35, 44], [11, 44, 7, 11]]
How It Works
The sorting process works as follows:
The
multiple_sort_valfunction counts elements divisible by K in each row usingele % K == 0Row
[92, 92, 5]has 0 multiples of 11, so it comes firstRow
[7, 5, 44, 11]has 1 multiple of 11 (the number 11)Row
[11, 6, 35, 44]has 1 multiple of 11 (the number 11)Row
[11, 44, 7, 11]has 2 multiples of 11 (both 11s), so it comes last
Using Lambda Function
You can also use a lambda function for more concise code ?
my_list = [[11, 44, 7, 11], [7, 5, 44, 11], [11, 6, 35, 44], [92, 92, 5]]
K = 11
# Sort using lambda function
my_list.sort(key=lambda row: len([ele for ele in row if ele % K == 0]))
print("Sorted list:")
print(my_list)
Sorted list: [[92, 92, 5], [7, 5, 44, 11], [11, 6, 35, 44], [11, 44, 7, 11]]
Conclusion
Sorting by K multiples uses a custom key function that counts divisible elements in each row. The sort() method with a key parameter arranges rows in ascending order based on the count of multiples.
