Python – Sort row by K multiples


When it is required to sort a row by multiples of K, a method is defined that uses list comprehension and the modulus operator.

Below is a demonstration of the same −

Example

 Live Demo

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)

Output

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]]

Explanation

  • A method is defined that takes a list as a parameter.

  • 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.

  • The size of this list is returned as output.

  • Outside the method, a list of list is defined and is displayed on the console.

  • A value for K is defined and is displayed on the console.

  • The list is sorted using the ‘sort’ method by specifying the key as the previously defined method.

  • This is the output which is displayed on the console.

Updated on: 04-Sep-2021

97 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements