python3中数组逆序输出方法
作者:laozhang 时间:2022-08-12 22:25:56
我们可以很轻松的从1到9或者从9到1正着背一遍,反着背一遍。但是想要在编程实现这些看起来简单的操作,就没那么容易了。因为计算机需要一些指令,去告诉它数字或是其他的内容进行逆序的代码。既然我们之前已经学了不少倒序的方法了,今天我们就进入实战,看看在数组中的逆序是如何输出的吧。
将一个数组逆序输出,用第一个与最后一个交换。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
if __name__ == '__main__':
a = [9,6,5,4,1]
N = len(a)
print a
for i in range(len(a) / 2):
a[i],a[N - i - 1] = a[N - i - 1],a[i]
print a
以上实例输出结果为:
[9, 6, 5, 4, 1]
[1, 4, 5, 6, 9]
拓展:
原本文件中是abcd,想把这四行按照dcba的顺序写进一个新文件
解决:
先读取文件到列表,然后对列表逆序,然后循环写入到新的文件
content = []
with open("name.txt" ) as f:
for row in f.readline():
content.append(row)
content.reverse()
with open("name1.txt","w" ) as f:
for row in content:
f.write(row)
f.write("\n")
看完本篇的逆序输出,相信不少小伙伴们都可以自己写一遍代码了,毕竟代码方面没有复杂的地方。
来源:https://www.py.cn/jishu/jichu/21448.html
标签:python3,数组,逆序输出
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解在OpenCV中实现的图像标注技术
2023-12-01 11:54:34
![](https://img.aspxhome.com/file/2023/3/99533_0s.jpg)
详解python里使用正则表达式的全匹配功能
2023-12-29 17:10:14
深入研究PHP中的preg_replace和代码执行
2023-11-22 07:36:55
![](https://img.aspxhome.com/file/2023/6/106316_0s.png)
python利用scatter绘画散点图
2021-02-02 01:45:37
![](https://img.aspxhome.com/file/2023/6/94166_0s.png)
使用正则表达式找出不包含特定字符串的条目
2010-03-02 22:06:00
![](https://img.aspxhome.com/file/UploadPic/20103/2/image_thumb-80s.png)
Python线程同步的实现代码
2022-10-01 00:20:48
python统计字母、空格、数字等字符个数的实例
2022-10-04 12:02:29
python利用paramiko连接远程服务器执行命令的方法
2021-07-19 01:07:34
Python 基于FIR实现Hilbert滤波器求信号包络详解
2023-07-13 01:31:47
![](https://img.aspxhome.com/file/2023/3/92433_0s.jpg)
如何用python合并多个excel文件
2022-08-23 19:30:24
![](https://img.aspxhome.com/file/2023/2/81822_0s.png)
Python+OpenCV实现基于颜色的目标识别
2022-10-28 02:57:27
![](https://img.aspxhome.com/file/2023/2/93592_0s.jpg)
numpy.reshape(-1,1)的具体使用
2021-12-26 13:25:30
python中使用np.delete()的实例方法
2023-02-07 10:19:47
LZ77 算法的JS实现
2010-04-11 22:32:00
php解析字符串里所有URL地址的方法
2023-08-19 08:31:38
在Python中使用HTML模版的教程
2023-01-17 23:30:38
![](https://img.aspxhome.com/file/2023/1/103111_0s.png)
不得不承认:韩国的 Web 设计很唯美
2009-05-13 13:26:00
![](https://img.aspxhome.com/file/UploadPic/20095/13/1221540-46s.jpg)
DBA_2PC_PENDING 介绍
2009-02-28 10:59:00
vscode 远程调试python的方法
2021-09-07 23:00:59
![](https://img.aspxhome.com/file/2023/7/83717_0s.png)
用 SA FileUp 上传多文件
2008-07-04 13:44:00