- Trending Categories
- Data Structure
- Operating System
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Sort row by K multiples
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 −
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]]
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.
- Python – Sort Matrix by Row Median
- Python - Sort Matrix by Maximum Row element
- Python - Sort rows by Frequency of K
- Python – Sort String list by K character frequency
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Sort elements of the array that occurs in between multiples of K in C++
- Python – Sort by range inclusion
- Python – Sort by Uppercase Frequency
- Python – Sort Dictionaries by Size
- Python – Convert String to matrix having K characters per row
- Python – Trim tuples by K
- Sort Array By Parity in Python
- Python – Sort Strings by Case difference
- Python – Sort Matrix by total characters
- Python – Sort Tuples by Total digits