内置函数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 = False 表示升序(默认)。

sorted 会返回一个新的list。

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

list.sort 会原地修改源list,返回 None。

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

创建一个字典,按元素值排序。

d = {'a': 10, 'b': 9, 'c': 11, 'd': 1, 'e': 5}
sorted(d.items(), key=lambda x: x[1])
# [('d', 1), ('e', 5), ('b', 9), ('a', 10), ('c', 11)]

参考文档

posted @ 2017-10-16 02:06  KeithTt  阅读(746)  评论(0编辑  收藏  举报