- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
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 Matrix by None frequency
When it is required to sort a matrix by ‘None’ frequency, a method is defined that takes a parameter and uses list comprehension, ‘not’ operator and ‘len’ method to determine the result.
Example
Below is a demonstration of the same −
def get_None_freq(row): 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("The list is : ") print(my_list) my_list.sort(key = get_None_freq) print("The result is : ") print(my_list)
Output
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]]
Explanation
A method named ‘get_None_freq’ is defined that takes a list as a parameter, and uses list comprehension to iterate over the elements and uses ‘not’ operator to check if an element is not present in the list, and determines its length.
This length is returned as output.
Outside the method, a list is defined and displayed on the console.
The list is sorted using the ‘sort’ method and the key is specified as the previously defined method.
This is the output that is displayed on the console.
Advertisements