Python – Sort row by K multiples

PythonServer Side ProgrammingProgramming

<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 &minus;</p><h2>Example</h2><p><a class="demo" href="http://tpcg.io/J6WcYGKN" rel="nofollow" target="_blank">&nbsp;Live Demo</a></p><pre class="prettyprint notranslate">def multiple_sort_val(row): &nbsp; &nbsp;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(&quot;The list is :&quot;) print(my_list) K = 11 print(&quot;The value for K is &quot;) print(K) my_list.sort(key=multiple_sort_val) print(&quot;The resultant list is :&quot;) 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 &lsquo;len&rsquo; 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 &lsquo;sort&rsquo; 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>
raja
Updated on 04-Sep-2021 11:00:24

Advertisements