python - 计数器 : ordering elements with equal counts

标签 python python-3.x collections

文档指定 collections.Counter.most_common() ,

elements with equal counts are ordered arbitrarily.

我对一种简洁的方式很感兴趣,它首先按频率/值降序(默认)排序,然后再按键升序排序。 (键只是 .most_common() 中每个元组的第 0 个元素。)

例子:

from collections import Counter
arr1 = [1, 1, 1, 2, 2, 3, 3, 3, 5]
arr2 = [3, 3, 3, 1, 1, 1, 2, 2, 5]  # Same values, different order

print(Counter(arr1).most_common())
print(Counter(arr2).most_common())
# [(1, 3), (3, 3), (2, 2), (5, 1)]
# [(3, 3), (1, 3), (2, 2), (5, 1)]

期望的结果(对于 arr2arr2):

[(1, 3), (3, 3), (2, 2), (5, 1)]

最佳答案

适当排序即可:

sorted(Counter(arr2).most_common(), key=lambda x: (-x[1], x[0]))

关于python - 计数器 : ordering elements with equal counts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46957889/

相关文章:

java - Sort native 方法 Java 的问题

python - 将鼠标悬停在 pandas 数据框上时如何注释标签

python - 连接两行,如果它们不为空

c# - 是否有更优雅的方式将项目安全地添加到 Dictionary<> 中?

python - 在 Python 中产生 2 次方的按位运算

正则表达式:如果组 2 不在组 3 和组 1 之间,则匹配 "group3.*group1"

c# - 使对象出列是否会从队列对象中删除引用并允许 GC?

python - 复制/ reshape 高维 numpy 数组

python - BeautifulSoup - lxml 和 html5lib 解析器抓取差异

python - 为什么我会收到此 Python 脚本的连接拒绝异常?