python列表中常见的一些排序方法
作者:Kristian-c 时间:2023-08-17 08:48:45
1、冒泡排序法
让列表中的一项和下一项作比较,若前一项大于后一项则交换两者位置(升序)。
方法一:直接使用for循环
L=[8,2,50,3]
for i in range(len(L)):
for j in range(i+1,len(L)):
if L[i]>L[j]:
L[i],L[j]=L[j],L[i]
print(L)
方法二:使用while语句
L=[8,2,50,3]
n=0
while n<len(L)-1:
n+=1
i=0
while i<len(L)-1:
if L[i]>L[i+1]:
L[i],L[i+1]=L[i+1],L[i]
i+=1
print(L)
2、选择排序法
在未排序的列表中找到最小元素,存放在列表的最前面,然后再从剩余的元素中寻找最小的,放到已排序列表的末尾,以此类推,直到所有元素排序完毕(升序)
方法一:remove和append同时使用
L=[8,2,50,3]
l=[] # 创建一个空列表用于存放排序后的数据
for i in range(len(L)):
a=min(L) # 创建一个变量存放最小值
l.append(a) # 向空列表中加入数据
L.remove(a) # 在原列表中将最小值剔除
print(l)
方法二:pop和append同时使用
L=[8,2,50,3]
# 创建函数寻找最小元素的索引值
def Smallest(L):
smallest = L[0]
s = 0 # 创建变量用于存放索引值
for i in range(1, len(L)):
if L[i] < smallest:
s = i
smallest = L[i]
return s # 返回最小元素的列表索引值
l = [] # 创建一个空列表用以存放排序后的数据
for i in range(len(L)):
smallest = Smallest(L)
l.append(L.pop(smallest)) # pop方法后跟元素当前列表最小值的索引值
print(l)
3、list.sort()方法
iterable.sort(self,key,reverse)
iterable以为可迭代对象,可以是列表、集合、字典
key是函数,指定取待排序元素的函数规则
reverse实现降序排序,需要提供一个bool值,默认为False(升序)
L=[8,2,50,3]
L.sort()
print(L)
4、sorted()函数
sorted(iterable,key=None,reverse=False)
key:通过这个参数可以自定义排序逻辑
L=[8,2,50,3]
l=sorted(L)
print(l)
来源:https://blog.csdn.net/m0_69265664/article/details/125703164
标签:python,列表,排序
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
3分钟看懂Python后端必须知道的Django的信号机制
2022-08-17 18:17:55
MySQL 复制表的方法
2024-01-21 02:22:50
![](https://img.aspxhome.com/file/2023/8/107428_0s.png)
VSCode 格式化缩进代码的实现
2023-01-22 15:22:49
![](https://img.aspxhome.com/file/2023/1/114681_0s.png)
python中的内置函数getattr()介绍及示例
2023-01-15 19:16:46
从Oracle 表格行列转置说起第1/2页
2009-09-24 12:51:00
微信小程序:报错(in promise) MiniProgramError
2024-05-09 10:35:18
![](https://img.aspxhome.com/file/2023/5/126855_0s.png)
python实现将html表格转换成CSV文件的方法
2023-08-25 00:48:41
用Python手把手教你实现2048小游戏
2023-02-22 23:27:57
![](https://img.aspxhome.com/file/2023/8/71578_0s.png)
go语言代码生成器code generator使用示例介绍
2024-05-21 10:19:29
![](https://img.aspxhome.com/file/2023/0/125070_0s.png)
Python中模拟enum枚举类型的5种方法分享
2022-05-04 01:00:10
pytorch tensor int型除法出现的问题
2021-05-18 13:18:17
![](https://img.aspxhome.com/file/2023/5/121155_0s.jpg)
Matplotlib 折线图plot()所有用法详解
2023-01-30 06:10:30
![](https://img.aspxhome.com/file/2023/6/99566_0s.png)
Python使用百度api做人脸对比的方法
2023-08-18 12:52:24
![](https://img.aspxhome.com/file/2023/7/68467_0s.jpg)
jQuery判断checkbox是否选中的3种方法
2024-04-22 13:05:16
![](https://img.aspxhome.com/file/2023/6/135846_0s.png)
mysql代码执行结构实例分析【顺序、分支、循环结构】
2024-01-21 23:18:40
![](https://img.aspxhome.com/file/2023/8/118238_0s.jpg)
mysql5.7创建用户授权删除用户撤销授权
2024-01-22 17:52:11
Python实现简单2048小游戏
2023-08-13 00:19:18
![](https://img.aspxhome.com/file/2023/3/71553_0s.jpg)
JDBC建立数据库连接的代码
2024-01-13 16:06:11
Python Flask框架实现简单加法工具过程解析
2021-08-17 20:36:11
![](https://img.aspxhome.com/file/2023/4/66864_0s.png)
简单代码屏蔽超级链接虚线框
2008-02-03 11:34:00