2017-02-07 2 views
0

Ich möchte die Wörter in einer Zeichenfolge (die Zeile) nach ihrer Länge sortieren und sie dann in der Liste nach der Anzahl der Wörter in jeder Zeile sortieren.Sortieren von Strings mit Wörtern in einer Liste

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

So würde der Ausgang sein:

hoot t 
phot o 
hot op 
tho op 
ho op t 
+1

Also, was ist Ihre Frage? –

+0

So sortieren Sie sie in Python –

+0

Bitte klären Sie Ihre Frage, indem Sie angeben, was Sie fragen, was Ihr Problem ist und was Sie bisher versucht haben. – Xenon

Antwort

1

Wenn ich es richtig verstanden habe, was es ist, dass Sie erreichen wollen, dies würde es tun:

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'] 
Verwandte Themen