python中sorted函数
sorted(iterable, *, key=None, reverse=False)
官方文档:https://docs.python.org/3/library/functions.html?highlight=sorted#sorted
Return a new sorted list from the items in iterable.
Has two optional arguments which must be specified as keyword arguments.
key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).
reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
Use functools.cmp_to_key() to convert an old-style cmp function to a key function.
The built-in sorted() function is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
其大意为:sorted函数返回一个新的可迭代的列表,sorted函数有两个可选参数,必须将其指定为关键字参数,key:用列表元素的某个属性或函数进行作为关键字,有默认值为None(直接与元素进行比较);reverse:一个bool变量,设置为True,为降序,设置为False,为升序。
用法
1、Sorting Basics
>>> sorted([5, 2, 3, 1, 4]) [1, 2, 3, 4, 5]
>>> a = [5, 2, 3, 1, 4] >>> a.sort() >>> a [1, 2, 3, 4, 5]
>>> sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'})
[1, 2, 3, 4, 5]
2、Key Functions
list.sort()和sorted()都有一个关键参数,用于指定在进行比较之前在每个列表元素上调用的函数。
>>> sorted("This is a test string from Andrew".split(), key=str.lower)
['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']
一种常见的模式是使用某些对象的索引作为关键字对复杂对象进行排序。 例如:
>>> student_tuples = [
... ('john', 'A', 15),
... ('jane', 'B', 12),
... ('dave', 'B', 10),
... ]
>>> sorted(student_tuples, key=lambda student: student[2]) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
同样的技术适用于具有命名属性的对象。 例如:
>>> class Student:
... def __init__(self, name, grade, age):
... self.name = name
... self.grade = grade
... self.age = age
... def __repr__(self):
... return repr((self.name, self.grade, self.age))
>>>
>>> student_objects = [
... Student('john', 'A', 15),
... Student('jane', 'B', 12),
... Student('dave', 'B', 10),
... ]
>>> sorted(student_objects, key=lambda student: student.age) # sort by age
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
2、Operator Module Functions
运算符模块具有itemgetter(),attrgetter()和methodcaller()函数,使用这些函数,上面的例子变得更简单和更快:
from operator import itemgetter, attrgetter
>>>
>>> sorted(student_tuples, key=itemgetter(2))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
>>>
>>> sorted(student_objects, key=attrgetter('age'))
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
下面更强大一个功能,Operator Module提供了一个更加强大的多级排序功能,例如:对于上例,先按照年级再按照年龄进行排序:
sorted(student_tuples, key=itemgetter(1,2))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
>>>
>>> sorted(student_objects, key=attrgetter('grade', 'age'))
[('john', 'A', 15), ('dave', 'B', 10), ('jane', 'B', 12)]
3、Ascending and Descending
list.sort()和sorted()接受带有布尔值的反向参数。 这用于标记降序排序。 例如,要以相反的年龄顺序获取学生数据:
>>> sorted(student_tuples, key=itemgetter(2), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
>>>
>>> sorted(student_objects, key=attrgetter('age'), reverse=True)
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
4、Sort Stability and Complex Sorts
排序保证稳定。 这意味着当多个记录具有相同的key时,它们的原始顺序将被保留
>>> data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]
>>> sorted(data, key=itemgetter(0))
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
这个独特的属性让你在一系列的排序步骤中建立复杂的排序。 例如,对学生数据先进行年级降级排序,再对年龄进行升序排序:
>>> s = sorted(student_objects, key=attrgetter('age')) # sort on secondary key
>>> sorted(s, key=attrgetter('grade'), reverse=True) # now sort on primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
4、The Old Way Using Decorate-Sort-Undecorate
这个idom使用三个步骤完成,Decorate、Sort、Undecorate,首先,初始list被控制排序的新值“装饰”;然后,decorated list进行排序;最后,decorated 被移除,创建一个按照新的排序的仅包含初始值的 list。
>>> decorated = [(student.grade, i, student) for i, student in enumerate(student_objects)]
>>> decorated.sort()
>>> [student for grade, i, student in decorated] # undecorate
[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]
在所有情况下,将索引 i 包含在“装饰清单”中,并不是绝对必要的,但包括它在内有两个好处:
排序是稳定的 - 如果两个 item 具有相同的键,他们的顺序将保存在排序列表中。
原始 item 不必是可比较的,因为 “装饰元组” 的排序将最多由前两项决定。 因此,例如,原始列表可能包含无法直接排序的complex numbers 。
优秀博客:https://www.cnblogs.com/sysu-blackbear/p/3283993.html
浙公网安备 33010602011771号