Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Sort rows by Frequency of K
When working with lists in Python, you may need to sort elements by their frequency of occurrence. This can be achieved using the Counter class from the collections module along with list comprehension.
Understanding the Problem
Sorting by frequency of 'K' means arranging elements so that the most frequently occurring items appear first, followed by less frequent ones. Elements with the same frequency maintain their relative order.
Example
Here's how to sort a list by element frequency using Counter.most_common() ?
from collections import Counter
my_list = [34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0]
print("The original list is:")
print(my_list)
# Sort by frequency using Counter and list comprehension
my_result = [item for items, c in Counter(my_list).most_common() for item in [items] * c]
print("The result sorted by frequency is:")
print(my_result)
The original list is: [34, 56, 78, 99, 99, 99, 99, 99, 12, 12, 32, 51, 15, 11, 0, 0] The result sorted by frequency is: [99, 99, 99, 99, 99, 0, 0, 12, 12, 32, 34, 11, 78, 15, 51, 56]
How It Works
Let's break down the solution step by step ?
from collections import Counter
data = [1, 3, 2, 1, 2, 1]
# Step 1: Count frequencies
counter = Counter(data)
print("Frequency count:", counter)
# Step 2: Get most common elements with their counts
most_common = counter.most_common()
print("Most common (element, count):", most_common)
# Step 3: Reconstruct list sorted by frequency
result = []
for element, count in most_common:
result.extend([element] * count)
print("Final sorted list:", result)
Frequency count: Counter({1: 3, 3: 1, 2: 2})
Most common (element, count): [(1, 3), (2, 2), (3, 1)]
Final sorted list: [1, 1, 1, 2, 2, 3]
Alternative Approach Using sorted()
You can also achieve the same result using the sorted() function with a custom key ?
from collections import Counter
numbers = [34, 56, 78, 99, 99, 99, 12, 12, 0, 0]
# Count frequencies
freq_count = Counter(numbers)
# Sort by frequency (descending) then by value (ascending) for ties
sorted_list = sorted(numbers, key=lambda x: (-freq_count[x], x))
print("Original list:", numbers)
print("Sorted by frequency:", sorted_list)
Original list: [34, 56, 78, 99, 99, 99, 12, 12, 0, 0] Sorted by frequency: [99, 99, 99, 0, 0, 12, 12, 34, 56, 78]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
Counter + List Comprehension |
Moderate | Good | Simple frequency sorting |
sorted() with key |
High | Good | Complex sorting criteria |
Conclusion
Use Counter.most_common() with list comprehension for straightforward frequency-based sorting. For more complex sorting requirements, prefer sorted() with a custom key function for better readability.
