【问题标题】:Counter: ordering elements with equal counts计数器:对具有相同计数的元素进行排序
【发布时间】:2018-04-08 01:07:22
【问题描述】:

文档指定collections.Counter.most_common()

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

我对一种简洁的方式感兴趣,首先按频率/值降序(默认)排序,然后按键升序排序。 (键是.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)]

【问题讨论】:

    标签: python python-3.x collections


    【解决方案1】:

    适当地排序:

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

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 2012-04-15
      • 1970-01-01
      • 1970-01-01
      • 2017-08-25
      • 1970-01-01
      • 2012-03-29
      • 1970-01-01
      • 2021-02-12
      相关资源
      最近更新 更多