Python 如何按字符串长度和字母顺序排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4659524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to sort by length of string followed by alphabetical order?
提问by Adrian
I'm currently new to python and got stuck at this question, can't seem to find the proper answer.
我目前是 python 的新手并且被这个问题困住了,似乎找不到正确的答案。
question:Given a list of words, return a list with the same words in order of length (longest to shortest), the second sort criteria should be alphabetical. Hint: you need think of two functions.
问题:给定一个单词列表,按长度(最长到最短)顺序返回一个单词相同的列表,第二个排序条件应该是字母顺序。提示:你需要考虑两个函数。
This is what I have so far:
这是我到目前为止:
def bylength(word1,word2):
return len(word2)-len(word1)
def sortlist(a):
a.sort(cmp=bylength)
return a
it sorts by length but I don't know how to apply the second criteria to this sort, which is by alphabetical descending.
它按长度排序,但我不知道如何将第二个标准应用于这种排序,即按字母降序排列。
采纳答案by Jochen Ritzel
You can do it in two steps like this:
您可以分两步完成,如下所示:
the_list.sort() # sorts normally by alphabetical order
the_list.sort(key=len, reverse=True) # sorts by descending length
Python's sort is stable, which means that sorting the list by length leaves the elements in alphabetical order when the length is equal.
Python 的排序是稳定的,这意味着当长度相等时,按长度对列表进行排序会使元素按字母顺序排列。
You can also do it like this:
你也可以这样做:
the_list.sort(key=lambda item: (-len(item), item))
Generally you never need cmp, it was even removed in Python3. keyis much easier to use.
通常你永远不需要cmp,它甚至在 Python3 中被删除了。key使用起来要容易得多。
回答by Arindam Roychowdhury
n = ['aaa', 'bbb', 'ccc', 'dddd', 'dddl', 'yyyyy']
for i in reversed(sorted(n, key=len)):
print i
yyyyy dddl dddd ccc bbb aaa
yyyyy dddl dddd ccc bbb aaa
for i in sorted(n, key=len, reverse=True):
print i
yyyyy dddd dddl aaa bbb ccc
yyyyy dddd dddl aaa bbb ccc
回答by jyfar
-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']
回答by theannouncer
Although Jochen Ritzel said you don't need cmp, this is actually a great use case for it! Using cmp you can sort by length and then alphabetically at the same time in half the time sorting twice would take!
尽管 Jochen Ritzel 说您不需要 cmp,但这实际上是一个很好的用例!使用 cmp 您可以按长度排序,然后同时按字母顺序排序,而两次排序所需的时间只有一半!
def cmp_func(a, b):
# sort by length and then alphabetically in lowercase
if len(a) == len(b):
return cmp(a, b)
return cmp(len(a), len(b))
sorted_the_way_you_want = sorted(the_list, cmp=cmp_func)
Example:
例子:
>>> the_list = ['B', 'BB', 'AA', 'A', 'Z', 'C', 'D']
>>> sorted(the_list, cmp=cmp_func)
['A', 'B', 'C', 'D', 'Z', 'AA', 'BB']
Note, if your list is a mix of upper and lower case replace cmp(a, b)with cmp(a.lower(), b.lower())as python sorts 'a' > 'Z'.
请注意,如果您的列表是大写和小写的混合,请替换cmp(a, b)为cmp(a.lower(), b.lower())as python 排序 'a' > 'Z'。
In python3 you'd need to be sorting objects with __lt__style comparison functions defined or functools.cmp_to_key()which does that for you.
在python3中,您需要使用__lt__定义的样式比较函数或为您执行此操作的对象对对象进行排序functools.cmp_to_key()。

