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

相关推荐
王小王-1235 分钟前
基于Python的车联网数据聚合与可视化分析平台设计与实现
python·车联网·新能源汽车·车联网聚合分析
叫我:松哥32 分钟前
基于Flask框架的校园二手书籍交易平台,注重校园场景的特殊需求,通过学号认证保障用户真实性
后端·python·sqlite·flask·bootstrap
namexingyun44 分钟前
开源前端生态如何成为 AI UI 生成的“燃料“:shadcn/ui、Tailwind CSS、Storybook 技术价值全解剖
java·前端·人工智能·python·ui·开源·ai编程
通信仿真爱好者1 小时前
第【17】期--考虑硬件损伤和不完美CSI的RIS-MISO系统的深度强化学习联合优化-python完整代码+参考文献
python·深度强化学习·ris
装不满的克莱因瓶1 小时前
自然语言处理常见任务——从文本理解到生成式AI的完整任务体系
人工智能·pytorch·python·深度学习·ai·自然语言处理
ptc学习者1 小时前
python 中描述符@property property 大概的样子
开发语言·python
zmzb01031 小时前
Python课后习题训练记录Day129
开发语言·python
秋91 小时前
Python工程师面试常问提问和回答(AI工程化方向 · 2026版)
人工智能·python·面试
炎武丶航1 小时前
LeNet-5深度学习详解:从手写数字识别到代码实战
人工智能·python·深度学习·机器学习·ai·cnn·lenet
sitellla1 小时前
Pydub:用 Python 处理音频,不写废话
开发语言·python·其他·音视频