python输出列表里最长的单词,Python-从列表中打印多个最短和最长的单词

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)

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值