【列表倒序】详解python列表倒序的几种方法(切片、reverse()、reversed())
2023-09-27 14:20:14 时间
1、切片
使用切片来实现列表的倒序排序,mylist[start:end:step],不改变原列表。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
if __name__ == '__main__':
a = [1, 2, 3, 4, 5, 6]
# 使用切片来实现列表倒序
print(a[::-1])
print(a)
输出:
[6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6]
Process finished with exit code 0
2、使用reverse()方法
使用reverse()方法对列表进行倒序,作用在原列表上,会改变原列表的顺序,返回值为none。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
if __name__ == '__main__':
a = [1, 2, 3, 4, 5, 6]
# 使用reverse()方法来实现列表倒序
a.reverse()
print(a)
输出:
[6, 5, 4, 3, 2, 1]
Process finished with exit code 0
3、使用reversed()方法
使用reversed()方法对列表进行倒序,将倒序结果存储在迭代器里面,不会改变原列表的顺序。
#!/usr/bin/env python
# -*- coding:utf-8 -*-
if __name__ == '__main__':
a = [1, 2, 3, 4, 5, 6]
# 使用reversed()方法来实现列表倒序
print(list(reversed(a)))
print(a)
输出:
[6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6]
Process finished with exit code 0
相关文章
- How to clear the interpreter console? Python
- python列表与数组的效率对比
- Python统计列表中的重复项出现的次数的方法
- python 对列表去重,并保持列表原来顺序
- python删除列表元素remove,pop,del
- python创建与遍历List二维列表
- 使用python 搭建web服务器
- 详解Python列表(list)的方法sort()的第一个参数key【简单清晰明了的讲解】
- 18 python - 列表
- python面对对象-使用@property
- python & shell实现业务高峰期临时动态增加服务器
- Python爬虫技术--基础篇--多进程
- 【Python】【排序】字符串列表排序/题目排序/首字母排序
- python实现散列表的链表法
- python实现散列表的直接寻址法
- 《Python数据分析》一2.9 基于位置列表的索引方法
- Python 列表、元素、字典
- python 列表对象的增减
- python 列表创建
- 我的Python程序太慢了。如何加快速度?
- python之获取包里面的所有模块列表
- python之enumerate函数:获取列表中每个元素的索引和值
- python中向array数组传递列表list的数值
- 文档转换python代码
- python数据相关性分析 (计算相关系数)
- python第三十课--异常(异常对象传递过程)
- Python列表函数和方法
- python将h264文件视频转为mp4格式
- [Python] 列表推导式