Sorting based on frequency and alphabetical order

穿精又带淫゛_ 提交于 2020-12-13 20:58:25

问题


I am trying to sort based on frequency and display it in alphabetical order After freq counting , I have a list with (string, count) tuple E.g tmp = [("xyz", 1), ("foo", 2 ) , ("bar", 2)]

I then sort as sorted(tmp, reverse=True) This gives me [("foo", 2 ) , ("bar", 2), ("xyz", 1)]

How can I make them sort alphabetically in lowest order when frequency same, Trying to figure out the comparator function

expected output:[("bar", 2), ("foo", 2 ), ("xyz", 1)]


回答1:


You have to sort by multiple keys.

sorted(tmp, key=lambda x: (-x[1], x[0]))

Source: Sort a list by multiple attributes?.




回答2:


Use this code:

from operator import itemgetter

tmp = [('xyz',1), ('foo', 2 ) , ('bar', 2)]
print(sorted(tmp, key=itemgetter(0,1)))

This skips the usage of function call.



来源:https://stackoverflow.com/questions/65113602/sorting-based-on-frequency-and-alphabetical-order

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!