本文介绍了在Python中按频率和值对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字列表,例如[2,2,3,3,4,1]我想按频率排序,如果频率计数(升序)相同,则按值排序(也升序).索恩应该是[1,4,2,2,3,3]

I have a list of numbers say, [2,2,3,3,4,1] I want to sort by frequency and if the frequency count (ascending) is same then sort by value (also ascending). Soln would be [1,4,2,2,3,3]

对于频率

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

但是我不确定如何对相同频率计数元素的值进行排序

But I am not sure how to sort by value for same frequency count elements

推荐答案

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

To follow up on @bro-grammer's comment (I used a tuple for the keys and called Counter only once):

此方法首先必须遍历列表进行计数,然后再进行其他一些排序.

There's this method which first has to go through the list for counting and then some more for sorting.

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

可能有一些聪明的算法可以将两者结合起来,但是我的直觉是,它将非常复杂,而且超出了您的需求

There's probably some clever algorithm that can somehow combine both of these but my intuition that it would be pretty complicated and more than you need

这篇关于在Python中按频率和值对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 07:15