Python - printing multiple shortest and longest words from a list

后端 未结 6 1417
旧时难觅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 06:10

    Volatility's answer is great, but let's look at another way to do this.

    What if you not only had the list in sorted order, but also had it grouped into batches of the same length? Then this would be easy: Print the first group, and print the last group.

    And there's a function that comes with Python that does that grouping for you, itertools.groupby, so it is easy:

    l.sort(key=len) # puts them in order
    groups = list(itertools.groupby(l, key=len))
    print('The shortest words are: {}'.format(groups[0][1])
    print('The longest words are: {}'.format(groups[-1][1])
    

    You could turn that into a one-liner:

    groups = list(itertools.groupby(sorted(l, key=len), key=len))
    

    However, I don't think I would in this case; that repeated key=len and all those extra parentheses make it harder to read.

    Meanwhile, you can avoid creating the whole list of groups when you only really want the first:

    l.sort(key=len)
    shortest = itertools.groupby(l, key=len)
    print('The shortest words are: {}'.format(next(shortest)[1]))
    longest = itertools.groupby(reversed(l), key=len)
    print('The longest words are: {}'.format(next(longest)[1]))
    

    However, unless the list is really huge, I wouldn't worry about this.

提交回复
热议问题