前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python中sort与sorted

python中sort与sorted

作者头像
听城
发布2018-04-27 14:58:51
6780
发布2018-04-27 14:58:51
举报
文章被收录于专栏:杂七杂八杂七杂八

sort与sorted是python中的排序函数。它们的最大区别在于sort是定义在list中的,对list起作用。而sorted则可以排序所有的可迭代对象

sort

首先我们来看一下sort的定义 L.sort(key=None, reverse=False),有两个可选参数key和reverse。key是排序的值,everse = True 降序 或者 reverse = False 升序

sort

sorted
代码语言:javascript
复制
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.

第一个参数为可迭代对象,其他参数同sort

sorted

我们可以看到sorted直接返回了一个列表,这也是它和sort不一样的一个地方,sort会修改原来的列表的值,sorted则直接返回一个列表。 下面介绍参数的使用:

代码语言:javascript
复制
import operator

L = [('d',2),('a',4),('b',3),('c',2)]
print(sorted(L))
print(sorted(L,reverse=True))
print(sorted(L,key=lambda x:x[1]))
print(sorted(L,key=operator.itemgetter(1)))

# [('a', 4), ('b', 3), ('c', 2), ('d', 2)]
# [('d', 2), ('c', 2), ('b', 3), ('a', 4)]
# [('d', 2), ('c', 2), ('b', 3), ('a', 4)]
# [('d', 2), ('c', 2), ('b', 3), ('a', 4)]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.10.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • sort
  • sorted
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档