Python - Sort rows by Frequency of K

PythonServer Side ProgrammingProgramming

When it is required to sort the rows by frequency of ‘K’, a list comprehension and ‘Counter’ methods are used.

Example

Below is a demonstration of the same

from collections import Counter

my_list = [34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0]

print ("The list is ")
print(my_list)

my_result = [item for items, c in Counter(my_list).most_common() for item in [items] * c]

print("The result is ")
print(my_result)

Output

The list is
[34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0]
The result is
[99, 99, 99, 99, 99, 0, 0, 12, 12, 32, 34, 11, 78, 15, 51, 56]

Explanation

  • The required packages are imported into the environment.

  • A list is defined and is displayed on the console.

  • A list comprehension is used to iterate over the elements and the 'most_Common' method is used on all elements.

  • This is converted to a list.

  • This is assigned to a variable.

  • The result is displayed on the console.

raja
Published on 16-Sep-2021 08:49:13
Advertisements