PrimuS PrimuS - 1 year ago 76
Python Question

Order list by occurance and alphabetical if tied

I am totally new to python and I already struggle with a fairly small task.

I have a wordlist, in which I want to count the (duplicate) words, show the top "n" words and in case of a tie, order them alphabetically.

For the first two parts I wrote this:

def count_words(s, n):

# TODO: Count the number of occurences of each word in s
wordlist = s.split()

#Count words
counts = Counter(wordlist)

#Get top n words
top_n = counts.most_common(n)

return top_n

but for
print count_words("cat bat mat cat cat mat mat mat bat bat cat", 3)
it gives me
[('mat', 4), ('cat', 4), ('bat', 3)]
, but I need it to be
[('cat', 4), ('mat', 4), ('bat', 3)]

Any hints appreciated!

Answer Source


top_n.sort(key=lambda x: (-x[1], x[0]))

right before the return. It sorts by the first element of the key, then, if there's a tie, by the second. Since it sorts from smallest to biggest, the first value is multiplied by -1.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download