对Counter中的键值对排序:按计数降序、同计数按名称排序
Hey there! Let’s work through this sorting problem you’re dealing with. You want your results sorted first by count in descending order, and when two items have the same count, you want them sorted by name—super straightforward once you know the trick.
Let’s Use an Example to Make It Clear
Suppose your current output looks like this (using a list of dictionaries as an example):
[ {"name": "Banana", "count": 2}, {"name": "Apple", "count": 3}, {"name": "Cherry", "count": 2}, {"name": "Blueberry", "count": 2} ]
And your desired output is:
[ {"name": "Apple", "count": 3}, {"name": "Banana", "count": 2}, {"name": "Blueberry", "count": 2}, {"name": "Cherry", "count": 2} ]
Solution in Python
To pull off this multi-condition sort, we’ll use Python’s built-in sorted() function with a custom key. The key will be a tuple that first sorts by negative count (to get descending order) and then by name (to handle ties):
# Your original data items = [ {"name": "Banana", "count": 2}, {"name": "Apple", "count": 3}, {"name": "Cherry", "count": 2}, {"name": "Blueberry", "count": 2} ] # Apply the sorted logic sorted_items = sorted(items, key=lambda x: (-x["count"], x["name"])) # Print the result for item in sorted_items: print(item)
If You’re Using JavaScript
The same logic applies here—we’ll use Array.sort() with a custom comparator function:
const items = [ {name: "Banana", count: 2}, {name: "Apple", count: 3}, {name: "Cherry", count: 2}, {name: "Blueberry", count: 2} ]; items.sort((a, b) => { // First sort by count descending if (b.count !== a.count) { return b.count - a.count; } // If counts are equal, sort by name ascending return a.name.localeCompare(b.name); }); console.log(items);
Core Idea for Any Language
No matter which language you’re working in, the core approach is the same:
- First priority: Sort by count in descending order.
- Second priority: When counts match, sort by name (ascending, or whatever order you need for names).
This two-tiered sorting will give you exactly the output you’re looking for!
内容的提问来源于stack exchange,提问作者monty




