Skip to main content
 首页 » 编程设计

python之在 Python 中按频率和值对列表进行排序

2025年05月04日20hnrainll

我有一个数字列表,比如 [2,2,3,3,4,1] 我想按频率排序,如果频率计数(升序)相同,则按值排序(也是升序)。 Soln 将是 [1,4,2,2,3,3]

对于频率

from collections import Counter 
print sorted(arr, key=Counter(arr).get) 

但我不确定如何对相同频率计数元素按值排序

请您参考如下方法:

跟进@bro-grammer 的评论(我使用了一个元组作为键并只调用了一次 Counter):

有一种方法,首先必须遍历列表进行计数,然后再进行一些排序。

from collections import Counter 
def perseus_sort(l): 
    counter = Counter(l) 
    return sorted(l, key=lambda x: (counter[x], x)) 

可能有一些聪明的算法可以以某种方式将这两者结合起来,但我的直觉是它会非常复杂并且超出你的需要