0

I want to sort the words in a string (the line) by their length, then sort them in the list by how many words are in each line.

list_of_words = ['hoop t','hot op','tho op','ho op t','phot o']

So the output would be:

hoot t
phot o
hot op
tho op
ho op t
martineau
  • 119,623
  • 25
  • 170
  • 301
Thomas Youngson
  • 181
  • 3
  • 14

1 Answers1

1

If I have understood correctly what it is you want to accomplish, this would do it:

list_of_words = ['hoop t','hot op','tho op','ho op t','phot o']

# first sort the words in each string by their length, from longest to shortest
for i, words in enumerate(list_of_words):
    list_of_words[i] = sorted(words.split(), key=len, reverse=True)

# second sort the list by how many words there are in each sublist
list_of_words.sort(key=lambda words: len(words))  # sorts list in-place

# third, join the words in each string back together into a single string
for i, words in enumerate(list_of_words):
    list_of_words[i] = ' '.join(words)

# show results
print(list_of_words)
['hoop t', 'hot op', 'tho op', 'phot o', 'ho op t']
martineau
  • 119,623
  • 25
  • 170
  • 301