2012-03-28 60 views
-2

可能重複:
how to sort by length of string followed by alphabetical order?輸出在最短的字的順序列表,以最長的單詞(蟒蛇)

我想創建一個打印單詞列表,以便程序從最短到最長的字符數。例如:

["My", "turtle", "is", "old"] 

將輸出:

"My" 
"is" 
"old" 
"turtle" 

有沒有什麼簡單的方法來做到這一點?我至今:

message = "My turtle is old" 
message = message.split(" ") 
+2

那麼在「最長到最短字符數」的代表中,這個代表怎麼樣? – bernie 2012-03-28 16:37:18

+1

可能的重複[如何按字符串的長度排序,然後按字母順序?](http://stackoverflow.com/questions/4659524/how-to-sort-by-length-of-string-followed-by-alphabetical - 順序),甚至更確切[基於字符串的長度排序Python列表](http://stackoverflow.com/questions/2587402/sorting-python-list-based-on-the-length-of-the-字符串),我用google搜索「python按長度排序」。 – agf 2012-03-28 16:40:28

+1

爲什麼標題最短最長,問題從最長到最短?下定決心:D – Dikei 2012-03-28 16:43:46

回答

0

排序爲.sort()輸入使用key關鍵詞長度:

l = ["My", "turtle", "is", "old"] 
l.sort(key=len) 

for i in l: 
    print i