前言

python的排序有两个方法,一个是list对象的sort方法,另外一个是builtin函数里面sorted,主要区别:

  • sort仅针对于list对象排序,无返回值, 会改变原来队列顺序
  • sorted是一个单独函数,可以对可迭代(iteration)对象排序,不局限于list,它不改变原生数据,重新生成一个新的队列

本篇是基于python3.6讲解的,python2会多一个cmp参数,cmp函数在python3上已经丢弃了

cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1。

sort方法

1.sort是list对象的方法,通过.sort()来调用

>>> help(list.sort)
Help on method_descriptor: sort(...)
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* >>>

2.参数说明:

  • key 用列表元素的某个属性或函数进行作为关键字(此函数只能有一个参数)

  • reverse 排序规则. reverse = True 降序 或者 reverse = False 升序,默认升序

  • return 无返回值

3.使用方法介绍

# coding:utf-8

a = [-9, 2, 3, -4, 5, 6, 6, 1]

# 按从小到大排序
a.sort()
print(a) # 结果:[-9, -4, 1, 2, 3, 5, 6, 6] # 按从大到小排序
a.sort(reverse=True)
print(a) # 结果:[6, 6, 5, 3, 2, 1, -4, -9]

4.key参数接受的是函数对象,并且函数只能有一个参数,可以自己定义一个函数,也可以写个匿名函数(lambda)

# coding:utf-8

a = [-9, 2, 3, -4, 5, 6, 6, 1]
# 按绝对值排序
def f(x):
return abs(x)
a.sort(key=f)
print(a) # 结果:[1, 2, 3, -4, 5, 6, 6, -9] # 1、list对象是字符串
b = ["hello", "helloworld", "he", "hao", "good"]
# 按list里面单词长度倒叙
b.sort(key=lambda x: len(x), reverse=True)
print(b) # 结果:['helloworld', 'hello', 'good', 'hao', 'he'] # 2、.list对象是元组
c = [("a", 9), ("b", 2), ("d", 5)] # 按元组里面第二个数排序
c.sort(key=lambda x: x[1])
print(c) # 结果:[('b', 2), ('d', 5), ('a', 9)] # 3、list对象是字典
d = [{"a": 9}, {"b": 2}, {"d":5}] d.sort(key=lambda x: list(x.values())[0])
print(d) # 结果:[{'b': 2}, {'d': 5}, {'a': 9}]

sorted函数

1.sorted是python里面的一个内建函数,直接调用就行了

>>> 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. >>>

2.参数说明

  • iterable 可迭代对象,如:str、list、tuple、dict都是可迭代对象(这里就不局限于list了)

  • key 用列表元素的某个属性或函数进行作为关键字(此函数只能有一个参数)

  • reverse 排序规则. reverse = True 降序或者 reverse = False 升序,默认升序

  • return 有返回值值,返回新的队列

3.使用方法介绍

# coding:utf-8

a = [-9, 2, 3, -4, 5, 6, 6, 1]

# 按从小到大排序
b = sorted(a)
print(a) # a不会变
print(b) # b是新的队列 [-9, -4, 1, 2, 3, 5, 6, 6] # 按从大到小排序
c = sorted(a, reverse=True)
print(c) # 结果:[6, 6, 5, 3, 2, 1, -4, -9]

4.可迭代对象iterable都可以排序,返回结果会重新生成一个list

# coding:utf-8

# 字符串也可以排序

s = "hello world!"
d = sorted(s)
print(d) # 结果:[' ', '!', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w'] # 元组也可以排序
t = (-9, 2, 7, 3, 5)
n = sorted(t)
print(n) # 结果:[-9, 2, 3, 5, 7] # dict按value排序
f = {"a": 9, "b": 2, "d": 5}
g = sorted(f.items(), key=lambda x: x[1])
print(g) # 结果:[('b', 2), ('d', 5), ('a', 9)]

python自动化交流 QQ群:779429633

python笔记18-sort和sorted区别的更多相关文章

  1. python排序函数sort()与sorted()区别

    sort是容器的函数:sort(cmp=None, key=None, reverse=False) sorted是python的内建函数:sorted(iterable, cmp=None, key ...

  2. sort 与 sorted 区别

    sort 与 sorted 区别: sort 只是应用在 list 上的方法,(就地排序无返回值). sorted 是内建函数,可对所有可迭代的对象进行排序操作,(返回新的list). 语法 sort ...

  3. sort 与 sorted 区别:

    sort 与 sorted 区别: sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作. list 的 sort 方法返回的是对已经存在的列表进行操作,无返回值, ...

  4. python中list.sort()与sorted()的区别

    list.sort()和sorted()都是python的内置函数,他们都用来对序列进行排序,区别在于 list.sort()是对列表就地(in-place)排序,返回None:sorted()返回排 ...

  5. Python中的 sort 和 sorted

    今天在做一道题时,因为忘了Python中sort和sorted的用法与区别导致程序一直报错,找了好久才知道是使用方法错误的问题!现在就大致的归纳一下sort和sorted的用法与区别 1. sort: ...

  6. python中的sort、sorted、reverse、reversed详解

    python语言中的列表排序方法有三个:reverse反转/倒序排序.sort正序排序.sorted可以获取排序后的列表.在更高级列表排序中,后两中方法还可以加入条件参数进行排序. reverse() ...

  7. python中sort与sorted区别

    1.sort()函数 (只对list有用) sort(...) L.sort(key = None,reverse=False) key = 函数 这个函数会从每个元素中提取一个用于比较的关键字.默认 ...

  8. python sort和sorted区别。

    前者是方法,后者是函数.oop和opp区别的经典体现.好好领会,就能知道什么时候写类什么时候写函数好.

  9. python中的sort和sorted

    共同点 都有三个参数, cmp用户自定义(指定函数),每个元素都会调用,效率没key高 key带一个参数的函数,用来为每个元素提取比较值 reverse=True    翻转 sort sort作用的 ...

  10. python list列表sort、sorted、reverse排序

    列表排序:sort是修改原列表,sorted提供原列表的一个有序副本 li=[2,1,4,5,0]li.sort() #默认从小到大print li结果:[0, 1, 2, 4, 5] li=[2,1 ...

随机推荐

  1. nio笔记

    http://blog.csdn.net/z69183787/article/category/2191483此人的博客 首先你要知道阻塞和非阻塞的概念,阻塞体现在这个线程不能干别的了,只能在这里等着 ...

  2. 一键去除网页BOM属性【解决乱码,头部空白,&#65279问题】

    几个常出现的问题: 1.网站打开空白 2.页面头部出现多余的空白 3.网站出现乱码,如“锘�” 解决方法可以是: 1.选用专业的编辑器,例如notepad++,sublime,editplus这样不会 ...

  3. coding.net--多人合作开发git的使用

    // 从conding拉下新项目 mkdir test cd test git clone https // 安装cocoapods gem sources --remove https://ruby ...

  4. Js添加、读取、删除cookie,判断cookie是否有效,指定domain域下主路径path下设置cookie,设置expires过期时间

    有时我们需要用cookie保存用户名,记录登录状态,如何正确判断该机用户cookie是否存在呢?不能简单使用a!=”这样的写法. 正确方法是:判断是否存在名为username3的cookie,使用do ...

  5. 安装matplotlib 和Pygal

    一.  在Linux系统中安装matplotlib 如果我们使用的是系统自带的Python版本,可使用系统的包管理器来安装matplotlib,为此只需执行一行命令: $ sudo apt-get i ...

  6. C++ 字符串基本操作

    C++ 规定,不能直接进行数组名的赋值,因为数组名是一个常量,而结构类型的变量可以赋值,不同结构体的变量不允许相互赋值,即使这两个变量可能具有相同的成员.在程序中不能同时出现无参构造函数和带有全部默认 ...

  7. vscode debugger for chrome 调试webpack的配置问题

    module.exports = { entry: './app.ts', output: { filename: 'bundle.js', publicPath: '/assets', devtoo ...

  8. linux 把ls -R格式化成树状结构

    谁能写脚本把linux中的ls -R命令的结果格式化成树状结构? 最好是shell脚本!欢迎讨论! 参与讨论有可能意外获取iPhone6哦~~

  9. CodeForces 909E Coprocessor

    题解. 贪心,拓扑排序. 和拓扑排序一样,先把$flag$为$0$的点能删的都删光,露出来的肯定都是$flag$为$0$的,然后疯狂删$flag$为$0$的,这些会使答案加$1$,反复操作就可以了. ...

  10. POJ 1976 A Mini Locomotive

    $dp$. 要求选择$3$个区间,使得区间和最大.$dp[i][j]$表示前$i$个数中选择了$j$段获得的最大收益. #include <cstdio> #include <cma ...