python中sorted()函数的排序用法、参数,实例详解

sorted()函数描述

sorted()是python的内置函数,可用于对python的可迭代对象iterable进行排序,可一至三个参数,返回一个已经根据参数设置进行相关排序的新的列表list,注意是新的list,并不对原来的对象进行修改。除此之外,与sort()的区别是,在python中,sort()是列表list有一个内置的属性方法,可用于列表list的排序,但是sort()却不可以用于其它的可迭代对象,如字符串、元组tuple、集合set等的排序。


sorted()函数参数结构语法

该语法来源于python的部分源码:

def sorted(iterable: Iterable[_T], key: Optional[Callable[[_T], Any]]=..., reverse: bool=...)

sorted()函数参数解析

  • iterable:第一个位置参数为可迭代对象,如字符串、list列表、tuple元组、dict字典、set集合等等;
  • key:关键词参数,一个可回调的应用于可迭代对象中各个元素的函数或排序规则;
  • reverse:值为True或False,默认为False,设置正序还是倒序的排序方法;

sorted()函数返回值

python源码中有这么一句话“Return a new list containing all items from the iterable in ascending order.”,即sorted()返回的是一个新的列表list。

sorted()函数实例代码

>>> a = [1,3,2]
>>> sorted(a)
[1, 2, 3]
>>> a
[1, 3, 2]
>>> b = (0,-1,-3)
>>> sorted(b,key=lambda x :x*x) #关键词参数key规定了sorted()对可迭代对象元素进行排序的规则
[0, -1, -3]
>>> sorted(b,key=lambda x:x*x, reverse=True) #reverse规定了sorted()排序的正序和倒序方法
[-3, -1, 0]
>>> b
(0, -1, -3)
>>> c = {"a":3,"b":1}
>>> sorted(c) #字典默认情况下根据dict的key进行排序
['a', 'b']
>>> c
{'a': 3, 'b': 1}
>>> sorted(c,key=lambda x:c[x]) #利用关键词参数key设置利用dict字典的value值进行排序
['b', 'a']

sorted()函数与sort()方法的排序区别

sorted()函数与sort()方法的排序比较大的一个区别是,sorted()可以为python的可迭代对象进行排序,而sort()一般只能用于list的排序,如下面的实例:

>>> a.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'sort'
>>> a = (1,3,2)
>>> a.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'sort'
>>> a = {1,3,2}
>>> a.sort()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'set' object has no attribute 'sort'

全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.