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的用法,并介绍了字典的两种排序方式。

相关推荐
黄昏恋慕黎明6 小时前
博客论坛技术迭代
python·pytest
我叫汪枫6 小时前
RAG 进阶:切分、检索、重排序,以及它和 Agent、微调、MCP 都是什么关系
开发语言·python
冰芒芒6 小时前
构建你的第一个 Agent 项目
python
gf13211116 小时前
【python_发送飞书卡片消息_直接组装JSON格式发送卡片】
python·json·飞书
lzqrzpt7 小时前
临沂LED驱动电源制造工艺解析与工程选型避坑指南
python·制造
ai小陈7 小时前
Python 3.12与CUDA 12.8镜像实战:启动GPU实例后的五项自检
开发语言·人工智能·python·深度学习·ai·gpu算力
Thomas.Sir7 小时前
第48课:TensorFlow|TF模型线上部署入门【本地服务封装、接口快速开发】
人工智能·python·tensorflow
Bruce_Liuxiaowei7 小时前
录屏片段无损合并:从 ffmpeg concat 原理到 Python 自动化脚本
python·ffmpeg·自动化
renzao_ai7 小时前
本地 35B 大模型部署实战:Ollama 跑 Ornith-35B 全流程
python·llama·免费ai大模型