python排序

0. 背景

Python排序功能十分强大,可以进行基本排序或自定义排序。Python中提供两种不同的排序方法对各种各样的数据类型进行排序。

1. 使用sorted()函数排序

排序主要是对相同数据类型 的元素进行的,包括数值和字符串两种数据类型。

1.1 对数值进行排序

对于包含数值元素的容器list, set, tuple以及dict,可以使用sorted函数进行排序

python 复制代码
>>> l = [3, 2, 7, 3, 4, 9]
>>> sorted(l)
[2, 3, 3, 4, 7, 9]

sorted函数的定义help(sorted)

python 复制代码
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.

sorted函数的性质:

  1. sorted函数不需要导入,属于全局函数
  2. 默认情况下,sorted函数对序列的元素进行升序排列
  3. sorted函数,返回一个新的有序输出序列,并且不改变原始序列的顺序
python 复制代码
>>> l = [3, 2, 7, 3, 4, 9]
>>> sorted_l = sorted(l)
>>> sorted_l
[2, 3, 3, 4, 7, 9]

当输入是一个集合或元组 时,输出结果仍然是一个列表,因为sorted函数根据定义返回一个新列表

python 复制代码
>>> t = (6, 3, 10, 5)
>>> sorted(t)
[3, 5, 6, 10]
>>> s = {4, 8, 2, 3}
>>> sorted(s)
[2, 3, 4, 8]

1.2 对字符串进行排序

sorted函数将一个str看作一个列表,并遍历其中的每一个元素。在一个字符串中,每一个元素都对应着str中的一个字符。sorted函数以相同的方式对待每一个句子,对每一个字符包括空格进行排序。可以通过字符串的join函数输出排序好的字符串。

python 复制代码
>>> str = "sdfgdas dasdf"
>>> str
'sdfgdas dasdf'
>>> sorted(str)
[' ', 'a', 'a', 'd', 'd', 'd', 'd', 'f', 'f', 'g', 's', 's', 's']
>>> "".join(sorted(str))
' aaddddffgsss'

2. 使用list.sort函数

list的成员函数sort定义

python 复制代码
help(list.sort)
Help on method_descriptor:

sort(...)
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*

list的成员函数sort性质

  1. sort是list类的一个方法,只能与list一起使用。
  2. sort返回None并改变 值(序列本身) 的位置
python 复制代码
>>> l
[3, 2, 7, 3, 4, 9]
>>> l.sort()
>>> l
[2, 3, 3, 4, 7, 9]

3. 对dict进行排序

3.1 使用sorted

python 复制代码
>>> d={'a':1,'c':3,'b':2}
>>> d.items()
dict_items([('a', 1), ('c', 3), ('b', 2)])
>>> d.keys()
dict_keys(['a', 'c', 'b'])
>>> d.values()
dict_values([1, 3, 2])
>>> sorted(d)
['a', 'b', 'c']
>>> sorted(d.keys())
['a', 'b', 'c']
>>> sorted(d.values())
[1, 2, 3]
>>> sorted(d.items(), key=lambda kv: kv[0])
[('a', 1), ('b', 2), ('c', 3)]
>>> sorted(d.items(), key=lambda kv: kv[1])
[('a', 1), ('b', 2), ('c', 3)]

3.2 使用列表的sort方法

Python中字典是无序类型,没有自己的排序方法。但是可以使用列表的sort方法 来进行排序。首先把字典转换为列表, 再进行排序。

python 复制代码
>>> d={'a':1,'c':3,'b':2}
>>> list(d)
['a', 'c', 'b']
>>> list(d.items())
[('a', 1), ('c', 3), ('b', 2)]
>>> l = list(d.items())
>>> l.sort(key=lambda kv:kv[1])
>>> l
[('a', 1), ('b', 2), ('c', 3)]

总结

本文介绍了python中可迭代对象如何进行排序,分析了全局函数sorted和列表局部函数sort的用法,并介绍了字典的两种排序方式。

相关推荐
允许部分打工人先富起来43 分钟前
在node项目中执行python脚本
前端·python·node.js
IVEN_1 小时前
Python OpenCV: RGB三色识别的最佳工程实践
python·opencv
haosend2 小时前
AI时代,传统网络运维人员的转型指南
python·数据网络·网络自动化
曲幽2 小时前
不止于JWT:用FastAPI的Depends实现细粒度权限控制
python·fastapi·web·jwt·rbac·permission·depends·abac
IVEN_19 小时前
只会Python皮毛?深入理解这几点,轻松进阶全栈开发
python·全栈
Ray Liang21 小时前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
AI攻城狮21 小时前
如何给 AI Agent 做"断舍离":OpenClaw Session 自动清理实践
python
千寻girling21 小时前
一份不可多得的 《 Python 》语言教程
人工智能·后端·python
AI攻城狮1 天前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维