Python-从列表中打印多个最短和最长的单词 [英] Python - printing multiple shortest and longest words from a list

查看:450
本文介绍了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.

我也尝试过:

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

这也与之前的代码相同

对于列表中最短的单词,我也需要这样做.

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.

推荐答案

实际上,您可以将现有代码修改为可以正常工作.而不是在s中保留单个字符串,而应在字符串中保留list字符串.如果找到与上一个最长的长度相同的长度,请append.如果您发现更长的时间,请扔掉list并重新开始.像这样:

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)

这篇关于Python-从列表中打印多个最短和最长的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆