按单一标准(字段或键)排序的正确 Python 成语是什么?

What is the right Python idiom for sorting by a single criterion (field or key)?

如标题所示,如何按单一标准对 objects 进行排序?

我听说过 key 参数、cmp 参数和 Decorate-Sort-Undecorate 模式。
我应该在现代 Python 中使用哪一个,如何使用?

在现代 Python 中,最好的方法是使用带有 key 参数的 list.sortsorted

当您传递 key 参数时,排序函数不会直接比较元素,而是比较 key 为它们返回的任何内容。

因此,您可以将任何将要排序的元素作为单个位置参数的可调用对象作为 key 传递,并且 returns 元素应按什么进行排序。
将为每个元素调用一次可调用对象。

一些简单的例子:

   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排序大致等同于Decorate-Sort-Undecorate pattern:

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 列表被排序。
元组由第一个 non-equal 元素进行比较。这是 key_,或者如果 key_ 相等,则 index。因为没有相等的索引,所以永远不会直接比较元素。
最后,元素从 decorated 中提取到新列表中,该列表被返回。

随机想法:

  • 可以使用 reverse=True
  • 反转排序元素的顺序
  • lambdas and functions from operator module 通常作为 key
  • 传递
  • 2.4之前,没有key参数。只有 Decorate-Sort-Undecorate pattern 和缓慢的 cmp 参数,
  • Sorting a Python list by two criteria.