
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 rows by Frequency of K
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.
- Related Questions & Answers
- Python – Sort String list by K character frequency
- Python – Sort by Uppercase Frequency
- Python – Sort Matrix by None frequency
- Python – Sort row by K multiples
- Program to sort array by increasing frequency of elements in Python
- Python program to sort tuples by frequency of their absolute difference
- Sort Characters By Frequency in C++
- Python Program to Sort Matrix Rows by summation of consecutive difference of elements
- Python Program to sort rows of a matrix by custom element count
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Python program to print Rows where all its Elements’ frequency is greater than K
- Delete elements with frequency atmost K in Python
- Python – Test if Rows have Similar frequency
- Python program to omit K length Rows
- Python – Filter rows with Elements as Multiple of K
Advertisements