Python - printing multiple shortest and longest words from a list

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

    You can use a dict to collect the words:

    results = {}
    for word in words:
       if len(word) not in results:
          results[len(word)] = []
       results[len(word)].append(word)
    

    Next sort the dictionary by the keys, which are the lengths and print the words. This prints the longest words first, to reverse it, remove reverse=True:

    for i in sorted(results.keys(), reverse=True):
       print 'Number of words with length {}: {}'.format(i,len(results[i]))
       for word in results[i]:
          print word
    

    To print only the shortest and longest:

    shortest = sorted(results.keys())[0]
    longest = sorted(results.keys(), reverse=True)[0]
    
    print 'Shortest words:'
    
    for word in results[shortest]:
       print word
    
    print 'Longest words:'
    
    for word in results[longest]:
       print word
    

提交回复
热议问题