
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort Rows by K-Multiples in Python
When it is required to sort a row by multiples of K, a method is defined that uses list comprehension and the modulus operator.
Below is a demonstration of the same −
Example
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)
Output
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]]
Explanation
A method is defined that takes a list as a parameter.
It uses list comprehension and the ‘len’ method to check if every list divided by a specific value of K results in 0 as the remainder or no.
The size of this list is returned as output.
Outside the method, a list of list is defined and is displayed on the console.
A value for K is defined and is displayed on the console.
The list is sorted using the ‘sort’ method by specifying the key as the previously defined method.
This is the output which is displayed on the console.
Advertisements