python sorted函数

python sorted函数是怎样的呢?下面就让我们一起来了解一下吧:

sorted()函数一般是用于对所有可迭代的对象进行排序操作。

它与sort 是有一定区别的,具体的区别是:

sort通常是应用在list上的方法,而sorted则能够对所有可迭代的对象进行排序操作。

list中的sort方法一般返回的是对已经存在的列表进行操作,无返回值,但是内建函数sorted方法返回的是一个新的list,因此它并不是在原有的基础上进行操作。

语法格式:

sorted(iterable, cmp=None, key=None, reverse=False)

参数:

iterable -- 可迭代对象。

cmp -- 比较的函数,这个具有两个参数,参数的值都是从可迭代对象中取出,此函数必须遵守的规则为,大于则返回1,小于则返回-1,等于则返回0。

key -- 主要是用来进行比较的元素,只有一个参数,具体的函数的参数就是取自于可迭代对象中,指定可迭代对象中的一个元素来进行排序。

reverse -- 排序规则,reverse = True 降序 , reverse = False 升序(默认)。

参考范例:

>>>a = [5,7,6,3,4,1,2]

>>> b = sorted(a) # 保留原列表

>>> a

[5, 7, 6, 3, 4, 1, 2]

>>> b

[1, 2, 3, 4, 5, 6, 7]

>>> L=[('b',2),('a',1),('c',3),('d',4)]

>>> sorted(L, cmp=lambda x,y:cmp(x[1],y[1])) # 利用cmp函数

[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

>>> sorted(L, key=lambda x:x[1]) # 利用key

[('a', 1), ('b', 2), ('c', 3), ('d', 4)]

>>> students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>> sorted(students, key=lambda s: s[2]) # 按年龄排序

[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

>>> sorted(students, key=lambda s: s[2], reverse=True) # 按降序

[('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]

>>>

以上就是小编的分享了,希望能够帮助到大家。

标签:python sorted函数

免责声明:本内容来自橡树街平台创作者或收集于互联网公开资源,不代表橡树街网的观点和立场。如有侵权内容,请联系我们删除。联系邮箱:ihuangque@qq.com
相关推荐
  • python enumerate函数
    python enumerate函数
    08-05
  • python中set()函数的用法
    python中set()函数的用法
    08-05
  • python排序函数
    python排序函数
    08-05
  • python能做什么
    python能做什么
    08-05
  • python开发工程师是做什么的
    python开发工程师是做什么的
    08-05
  • python什么意思
    python什么意思
    08-05
  • python sorted
    python sorted
    08-05
  • python自动化脚本
    python自动化脚本
    08-05
  • python主要是做什么的
    python主要是做什么的
    08-05
  • python可以用来做什么
    python可以用来做什么
    08-05