Python – Sort Matrix by None frequency

PythonServer Side ProgrammingProgramming

<p>When it is required to sort a matrix by &lsquo;None&rsquo; frequency, a method is defined that takes a parameter and uses list comprehension, &lsquo;not&rsquo; operator and &lsquo;len&rsquo; method to determine the result.</p><h2>Example</h2><p>Below is a demonstration of the same &minus;</p><pre class="demo-code notranslate language-python" data-lang="python">def get_None_freq(row): &nbsp; &nbsp;return len([element for element in row if not element]) my_list = [[None, 24], [None, 33, 3, None],[42, 24, 55], [13, None, 24]] print(&quot;The list is : &quot;) print(my_list) my_list.sort(key = get_None_freq) print(&quot;The result is : &quot;) print(my_list)</pre><h2>Output</h2><pre class="result notranslate">The list is : [[None, 24], [None, 33, 3, None], [42, 24, 55], [13, None, 24]] The result is : [[42, 24, 55], [None, 24], [13, None, 24], [None, 33, 3, None]]</pre><h2>Explanation</h2><ul class="list"><li><p>A method named &lsquo;get_None_freq&rsquo; is defined that takes a list as a parameter, and uses list comprehension to iterate over the elements and uses &lsquo;not&rsquo; operator to check if an element is not present in the list, and determines its length.</p></li><li><p>This length is returned as output.</p></li><li><p>Outside the method, a list is defined and displayed on the console.</p></li><li><p>The list is sorted using the &lsquo;sort&rsquo; method and the key is specified as the previously defined method.</p></li><li><p>This is the output that is displayed on the console.</p></li></ul>
Updated on 08-Sep-2021 10:46:16