Python - printing multiple shortest and longest wo

2020-03-26 03:55发布

问题:


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

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

This works but only prints the first longest, which is no good for more than one longest word.

I've also tried :

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

This also the same as the previous code

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

Apologies if this isn't a good question, it's my first.

回答1:

Your existing code could actually be modified to work without much trouble. Instead of keeping a single string in s, keep a list of strings. If you find one that's the same length as the previous longest, append it. If you find one that's even longer, throw out the 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:

Firstly, don't ever use list as a variable name as it will override the built in type and could cause trouble later on.

You could 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 the strings which have the same length as the longest string. The second does the same, but with the shortest strings.

A small optimisation would be to precalculate the max/min length before the loop, so you don't need 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 the other loop.



回答3:

Volatility's answer is great, but let's look at another way to do this.

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

And there's a function that comes with Python that does that grouping for you, itertools.groupby, so it is 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 could turn that into a one-liner:

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

However, I don't think I would in this case; that repeated key=len and all those extra parentheses make it harder to read.

Meanwhile, you can avoid creating the whole list of groups when you only really want the 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, unless the list is really huge, I wouldn't worry about this.



回答4:

You can use a dict to collect the words:

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

Next sort the dictionary by the keys, which are the lengths and print the 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


回答5:

Can always use a lambda function as well

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

will yield the longest words

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

Will yield the shortest words



回答6:

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