2017-02-07 23 views
0

文字列(行)の単語を長さで並べ替え、各行にいくつの単語があるかによって並べ替えます。リスト内の単語で文字列を並べ替える

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

ので、出力は次のようになります。

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

だからあなたは何でしょう質問? –

+0

Pythonで並べ替える方法 –

+0

質問していること、問題の内容、これまでに試したことを明記して質問を明確にしてください。 – Xenon

答えて

1

私はあなたが達成したいされているものを正しく理解している場合は、これはそれを行うだろう:

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'] 
関連する問題