Python - printing multiple shortest and longest words from a list


I need to go through a list and type the longest words in it. I can do it in just one word, but I can't figure out how to print more than one if, for example, there are two words that are three letters long. I tried

list.sort (key=len, reverse =True)
print ("The longest word in the list is: " , list[0])

      

This works, but only prints the longest one, which doesn't fit more than one long word.

I've also tried:

p=0
for item in list:
    if len (item) > p:
        s=item
        p = len(item)
print (s)

      

This is also the same as the previous code

I also need to do this for the shortest word in the list.

Sorry if this is not a very good question, this is my first one.

+3


source to share


6 answers


The existing code can indeed be modified to work without too much trouble. Instead of storing one line in s

, store the lines list

. If you find one that is the same length as the previous one append

,. If you find one that's even longer, throw it away list

and start a new one. Like this:



p=0
s=[]
for item in lst:
    if len(item) > p:
        s=[item]
        p=len(item)
    elif len(item) == p:
        s.append(item)
print(s)

      

+2


source


First, never use it list

as a variable name, as it will override the built-in type and may cause problems later.

You can do this for the longest words:

for i in lst:
    if len(i) == max(lst, key=len):
        print(i)

      

And for the shortest words:

for i in lst:
    if len(i) == min(lst, key=len):
        print(i)

      



The first code prints lines that are the same length as the longest line. The second does the same, but with the shortest lines.

A small optimization would be to pre-calculate the max / min length before the loop, so you don't have to recalculate it every time.

maxLen = max(lst, key=len)
for i in lst:
    if len(i) == maxLen:
        print(i)

      

The same can be done for another loop.

+3


source


The answer to volatility is great, but let's look at another way to do it.

What if you not only had a list in sorted order, but it was also grouped into batches of the same length? Then it will be easy: print the first group and print the last group.

And there is a function that comes with Python that does this grouping for you itertools.groupby

, so it's easy:

l.sort(key=len) # puts them in order
groups = list(itertools.groupby(l, key=len))
print('The shortest words are: {}'.format(groups[0][1])
print('The longest words are: {}'.format(groups[-1][1])

      

You can turn this into a one-liner:

groups = list(itertools.groupby(sorted(l, key=len), key=len))

      

However, I don't think I would in this case; which is repeated key=len

and all the extra parentheses make it difficult to read.

At the same time, you can avoid creating the entire list of groups when you really want to first:

l.sort(key=len)
shortest = itertools.groupby(l, key=len)
print('The shortest words are: {}'.format(next(shortest)[1]))
longest = itertools.groupby(reversed(l), key=len)
print('The longest words are: {}'.format(next(longest)[1]))

      

However, if the value is list

really big, I wouldn't bother with that.

+1


source


You can use a dict to collect words:

results = {}
for word in words:
   if len(word) not in results:
      results[len(word)] = []
   results[len(word)].append(word)

      

Next, compile a dictionary of keys that are long and type words. This prints the longest words first, to reverse it, remove reverse=True

:

for i in sorted(results.keys(), reverse=True):
   print 'Number of words with length {}: {}'.format(i,len(results[i]))
   for word in results[i]:
      print word

      

To print only the shortest and longest:

shortest = sorted(results.keys())[0]
longest = sorted(results.keys(), reverse=True)[0]

print 'Shortest words:'

for word in results[shortest]:
   print word

print 'Longest words:'

for word in results[longest]:
   print word

      

0


source


The lambda function can always be used

longest = len(sorted(list, key=len)[-1])
filter(lambda item: len(item) == longest, list)

      

will give the longest words

shortest = len(sorted(list, key=len)[0])
filter(lambda item: len(item) == shortest, list)

      

Here are the shortest words

0


source


list.sort (key=len, reverse =True)
print ("The longest 3 words in the list are: " , list[:3])

      

-1


source







All Articles