按单个条件(字段或键)排序的正确Python习惯用法是什么? [英] What is the right Python idiom for sorting by a single criterion (field or key)?

查看:81
本文介绍了按单个条件(字段或键)排序的正确Python习惯用法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与标题中一样,如何按单个条件对对象进行排序?

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.sortsortedkey参数一起使用.

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.

  • Order of sorted elements can be reversed using reverse=True,
  • lambdas and functions from operator module are often passed as key,
  • before 2.4, there were no key parameter. There were only Decorate-Sort-Undecorate pattern and slow cmp parameter,
  • Sorting a Python list by two criteria.

这篇关于按单个条件(字段或键)排序的正确Python习惯用法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆