计数器:具有相等计数的订购元素 [英] Counter: ordering elements with equal counts

查看:81
本文介绍了计数器:具有相等计数的订购元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

文档为 馆藏指定。 Counter.most_common()


具有相等计数的元素是任意排序的。

elements with equal counts are ordered arbitrarily.

我对一种简洁的方法感兴趣,即首先通过频率/值的降序(默认值)进行排序,然后通过键的升序进行排序。 (键只是 .most_common()中每个元组的第0个元素。)

I'm interested in a concise way to order first by frequency/value descending (the default), but then secondarily by key, ascending. (Key is just the 0th element of each tuple from .most_common().)

示例:

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)]

所需的结果(对于 arr2 arr2 而言):

Desired result (for both arr2 and arr2):

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


推荐答案

只需对其进行适当排序:

Just sort it appropriately:

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

这篇关于计数器:具有相等计数的订购元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆