We have a scenario where we have to pick the top n longest word from a list containing many words of varying length. In this article we will see various approaches to achieve that.
With count() and sorted()
We first sort the elements of the list in the reverse order so that the longest words are available at the beginning of the list. Then find the length of each word and add the result of the count to a variable. Finally take a slice of the required number of longest words we need.
Example
from itertools import count def longwords(l, x): c = count() return sorted(l, key=lambda i: (len(i), next(c)), reverse=True)[:x] listA = ['Earth','Moonshine','Aurora','Snowflakes','Sunshine'] n = 2 print(longwords(listA, n))
Output
Running the above code gives us the following result −
['Snowflakes', 'Moonshine']
With zip and enumerate
In this approach we use enumerate to list out each element of the list and then apply sorted and zip function to get the count. The negative length values indicate the reverse order of sorting and finally we slice the required number of counts.
Example
def longwords(l, x): idx, words = zip(*sorted(enumerate(l), key = lambda i: (-len(i[1]), -i[0]))[:x]) return list(words) listA = ['Earth','Moonshine','Aurora','Snowflakes','Sunshine'] n = 2 print(longwords(listA, n))
Output
Running the above code gives us the following result −
['Snowflakes', 'Moonshine']