2017-02-07 25 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']