Python - printing multiple shortest and longest words from a list

后端 未结 6 1372
旧时难觅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:48

    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.

提交回复
热议问题