Python - printing multiple shortest and longest words from a list

后端 未结 6 1421
旧时难觅i
旧时难觅i 2021-01-14 05:25


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

6条回答
  •  佛祖请我去吃肉
    2021-01-14 05:52

    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)
    

提交回复
热议问题