Python – Sort Matrix by None frequency

PythonServer Side ProgrammingProgramming

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.

raja
Published on 08-Sep-2021 10:46:16
Advertisements