按单个条件(字段或键)排序的正确Python习惯用法是什么? [英] What is the right Python idiom for sorting by a single criterion (field or key)?
问题描述
与标题中一样,如何按单个条件对对象进行排序?
As in title, how can I sort objects by single criterion?
我听说过key
参数,cmp
参数以及Decorate-Sort-Undecorate模式.
我应该在现代Python中使用哪一个,如何使用?
I've heard about key
parameter, cmp
parameter, and Decorate-Sort-Undecorate pattern.
Which one should I use in modern Python, and how?
推荐答案
在现代Python中,最好的方法是将list.sort
或sorted
与key
参数一起使用.
In modern Python, the best way is to use list.sort
or sorted
with key
argument.
当您传递key
参数时,排序函数(而不是直接比较元素)将比较为它们返回的任何key
.
When you pass key
argument, sorting function, instead of comparing elements directly, compares whatever key
returned for them.
因此,您可以将任何需要将元素作为单个位置参数进行排序的可调用项作为key
传递,并返回该元素应按什么排序.
每个元素都会被调用一次.
So, you can pass as key
any callable that takes element to be sorted as single positional argument, and returns what the element should be sorted by.
The callable will be called once for each element.
一些简单的例子:
list_ = ['B', 'aaa', 'CC']
sorted(list_)
=> ['B', 'CC', 'aaa']
# case-insensitive sorting
sorted(list_, key=str.lower)
=> ['aaa', 'B', 'CC']
# sorting by length
sorted(list_, key=len)
=> ['B', 'CC', 'aaa']
使用key
排序大致等于装饰-排序-装饰图案:
def decorate_sort_undecorate(iterable, key):
# 1: decorate:
decorated = [(key(elem), index, elem) for index, elem in enumerate(iterable)]
# 2: sort:
decorated.sort()
# 3: undecorate:
return [elem for key_, index, elem in decorated]
这将创建3元素元组的临时列表(decorated
),
格式为:(key_, index, elem)
,其中为key_ = key(elem)
.然后,对decorated
列表进行排序.
元组通过第一个非相等元素进行比较.这是key_
,或者如果key_
相等,则为index
.因为没有相等的索引,所以永远不会直接比较元素.
最后,元素从decorated
中提取到新列表中,并返回.
This creates temporary list (decorated
) of 3-element tuples,
which have form: (key_, index, elem)
, where key_ = key(elem)
. Then, decorated
list is sorted.
Tuples are compared by first non-equal element. This is key_
, or if key_
s are equal, index
. Because there are no equal indexes, elements are never directly compared.
At the end, elements are extracted from decorated
into new list, which is returned.
- 可以使用
reverse=True
反转排序元素的顺序 -
lambda
s 和装饰-排序-未装饰模式,并且cmp
参数 - 通过两个条件对Python列表进行排序.
- Order of sorted elements can be reversed using
reverse=True
, lambda
s and functions fromoperator
module are often passed askey
,- before 2.4, there were no
key
parameter. There were only Decorate-Sort-Undecorate pattern and slowcmp
parameter, - Sorting a Python list by two criteria.
这篇关于按单个条件(字段或键)排序的正确Python习惯用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!