

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Python – Sort row by K multiples
<p>When it is required to sort a row by multiples of K, a method is defined that uses list comprehension and the modulus operator.</p><p>Below is a demonstration of the same −</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/J6WcYGKN" rel="nofollow" target="_blank"> Live Demo</a></p><pre class="prettyprint notranslate">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)</pre><h2>Output</h2><pre class="result notranslate">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]]</pre><h2>Explanation</h2><ul class="list"><li><p>A method is defined that takes a list as a parameter.</p></li><li><p>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.</p></li><li><p>The size of this list is returned as output.</p></li><li><p>Outside the method, a list of list is defined and is displayed on the console.</p></li><li><p>A value for K is defined and is displayed on the console.</p></li><li><p>The list is sorted using the ‘sort’ method by specifying the key as the previously defined method.</p></li><li><p>This is the output which is displayed on the console.</p></li></ul>
- Related Questions & Answers
- 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++
- List expansion by K in Python
- Python – Trim tuples by K
- Sort Array By Parity in Python
- Python – Sort by range inclusion
- Python – Sort by Uppercase Frequency
- Python – Sort Dictionaries by Size
- Smallest Integer Divisible by K in Python
- Sort Tuples by Total digits in Python
- Sort Python Dictionaries by Key or Value
Advertisements