python多维列表按列表中某个值排序_在Python中按频率和值对列表进行排序

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]

For frequency

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

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值