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.
解决方案
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)