问题
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