gpt4 book ai didi

python - 计数器 : ordering elements with equal counts

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:33 25 4
gpt4 key购买 nike

文档指定 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com