内置函数sorted()

这里顺便说一下sorted()和sort()的异同。

sort 是 list 中的方法,只能对列表排序;sorted 可以对所有可迭代对象进行排序。
list 的 sort 方法是对原列表进行操作,而内置函数 sorted 会返回一个新的 list,而不是对原对象的操作。

>>> help(sorted)
Help on built-in function sorted in module builtins:
sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.   
    A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order.
>>> help(list.sort)
Help on method_descriptor:
sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

两个函数的两个可选参数相同。

  • key 给定一个函数,用来处理比较对象,然后通过函数返回结果进行比较。默认为None,直接按第一列排序。
  • reverse 是一个布尔值,用来指定排序方向。reverse = True 表示降序 , reverse = False 表示升序(默认)。

用sorted排序之后,会返回一个新的list,不影响原来的list。

>>> nums = [4,9,3,2,1,5,6,8,7]
>>> sorted(nums)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> nums
[4, 9, 3, 2, 1, 5, 6, 8, 7]

用sort排序之后,原list被改变。

>>> nums = [4,9,3,2,1,5,6,8,7]
>>> nums.sort()
>>> nums
[1, 2, 3, 4, 5, 6, 7, 8, 9]

创建一个字典,并转换为元祖列表。

>>> d={'a': 10, 'b': 9, 'c': 11, 'd': 1, 'e': 5}
>>> L=list(d.items())
>>> L
[('a', 10), ('b', 9), ('c', 11), ('d', 1), ('e', 5)]

利用lambda函数指定用元祖中的第二个元素排序。

>>> sorted(L,key=lambda x:x[1])
[('d', 1), ('e', 5), ('b', 9), ('a', 10), ('c', 11)]

不指定排序key即key为none时,默认按第一列直接排序。

>>> sorted(L)
[('a', 10), ('b', 9), ('c', 11), ('d', 1), ('e', 5)]
>>> L
[('a', 10), ('b', 9), ('c', 11), ('d', 1), ('e', 5)]

sort也可以按指定key排序。

>>> L.sort(key=lambda x:x[1])
>>> L
[('d', 1), ('e', 5), ('b', 9), ('a', 10), ('c', 11)]
>>> l = ['a', 4, 3, 2, 1, [1, 2]]
>>> l.sort(key=str, reverse=True)
>>> l
['a', [1, 2], 4, 3, 2, 1]

参考:https://docs.python.org/3/library/functions.html#sorted

原文地址:https://www.cnblogs.com/keithtt/p/7675283.html