2011-01-11 159 views
41

我目前是python的新手,被困在這個問題上,似乎無法找到正確的答案。如何按字符串的長度和字母順序排序?

問題:給出的單詞的列表,按長度順序返回具有相同的單詞列表(最長到最短),第二類標準應該是按字母順序排列。提示:你需要考慮兩個功能。

這是我到目前爲止有:

def bylength(word1,word2): 
    return len(word2)-len(word1) 

def sortlist(a): 
    a.sort(cmp=bylength) 
    return a 

它按長度,但我不知道如何將第二標準適用於這類,這是按字母順序降序排列。

+1

http://stackoverflow.com/questions/ 4655591/python-sort-list - 看起來像一個大cla的作業ssroom ... – eumiro 2011-01-11 15:56:27

回答

84

你可以做的兩個步驟是這樣的:

the_list.sort() # sorts normally by alphabetical order 
the_list.sort(key=len, reverse=True) # sorts by descending length 

Python的排序是穩定的,這意味着在長列表進行排序,葉按字母順序排列的元素時的長度相等。

你也可以做這樣的:

the_list.sort(key=lambda item: (-len(item), item)) 

一般來說,你永遠不需要cmp,有人甚至在Python3刪除。 key更容易使用。

+2

lambda解決方案是敬畏一些! – dmeu 2016-03-18 16:31:07

5
n = ['aaa', 'bbb', 'ccc', 'dddd', 'dddl', 'yyyyy'] 

for i in reversed(sorted(n, key=len)): 
    print i 

YYYYY dddl DDDD CCC AAA BBB

for i in sorted(n, key=len, reverse=True): 
    print i 

YYYYY DDDD dddl AAA BBB CCC

1
-Sort your list by alpha order, then by length. 

See the following exmple: 

>>> coursesList = ["chemistry","physics","mathematics","art"] 
>>> sorted(coursesList,key=len) 
['art', 'physics', 'chemistry', 'mathematics'] 
>>> coursesList.append("mopsosa") 
>>> sorted(coursesList,key=len) 
['art', 'physics', 'mopsosa', 'chemistry', 'mathematics'] 
>>> coursesList.sort() 
>>> sorted(coursesList,key=len) 
['art', 'mopsosa', 'physics', 'chemistry', 'mathematics']