python的reverse函数翻转结果为None的问题
作者:SieteDing 时间:2022-06-20 16:27:32
今天刷二级题的时候,遇到一个问题
>>> L2=[1,2,3,4]
>>> L3=L2.reverse()
>>> print( L3)
None
>>> print(L3)
None
>>> print(L2.reverse())
None
其实我想让它输出[4,3,2,1]
reverse函数,翻转列表
然后我改了一下
>>> L2.reverse()
>>> L3=L2
>>> print(L3)
[4, 3, 2, 1]
>>> print(L2)
[4, 3, 2, 1]
>>>
这是在网上找到的解释
a=[1,2,3,4].reverse() – why “a” is None?
看到其讨论说到:
b = [1,2,3,4] a = b.reverse() would change the value of b.
才想起来,原来这个reverse函数,针对列表的操作,其结果是直接改变列表本身(为了节省空间),所以,直接就把原先的list改为你所想要的reversed后的结果了,而返回值,是空的,不返回任何值。
所以,本身直接使用:
a.reverse(); # -> is OK, the self is reversed !!!
补充知识:Python中reverse与reverse=true
排序
a = [2, 3, 1]
a.sort(reverse=True)
print(a) # [3, 2, 1]
没有排序
a = [2, 3, 1]
a.reverse()
print(a) # [1, 3, 2]
来源:https://blog.csdn.net/weixin_42169849/article/details/88897132
标签:python,reverse,None
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pycharm第三方库安装失败的问题及解决经验分享
2023-07-11 01:50:45
![](https://img.aspxhome.com/file/2023/5/107035_0s.png)
Typecho插件实现添加文章目录的方法详解
2023-05-25 07:19:04
python使用装饰器和线程限制函数执行时间的方法
2022-04-03 04:06:34
当设计师遇上前端开发
2009-05-04 14:05:00
php pdo oracle中文乱码的快速解决方法
2023-11-16 22:12:47
Python多线程以及多线程中join()的使用方法示例
2021-02-07 16:25:03
![](https://img.aspxhome.com/file/2023/0/90600_0s.png)
使用PHP实现生成HTML静态页面
2023-11-14 11:14:41
MYSQL教程:MySQL Show命令
2009-12-20 17:54:00
TensorFlow2.0:张量的合并与分割实例
2022-12-02 13:44:49
python禁用键鼠与提权代码实例
2022-12-11 11:54:59
对numpy中shape的深入理解
2023-12-09 03:43:41
Python中常见的数据类型小结
2022-03-25 07:55:17
Python PaddleNLP开源实现快递单信息抽取
2023-01-21 04:35:11
![](https://img.aspxhome.com/file/2023/3/80603_0s.jpg)
jQuery 1.3的VS智能提示下载
2009-01-18 12:54:00
![](https://img.aspxhome.com/file/UploadPic/20091/18/ysc7nc_jquery_1-68s.gif)
基于PHP RSA密文过长加密解密 越过1024的解决方法
2023-09-07 02:57:56
Android ProgressBar进度条和ProgressDialog进度框的展示DEMO
2023-11-20 01:15:43
![](https://img.aspxhome.com/file/2023/1/95001_0s.jpg)
Asp无组件上传进度条解决方案
2010-04-24 16:01:00
python类的私有属性和公共属性说明
2021-04-07 11:03:59
我放弃Python转Go语言的9大理由(附优秀书籍推荐)
2022-05-27 04:46:17
![](https://img.aspxhome.com/file/2023/6/86296_0s.jpg)
详解python如何调用C/C++底层库与互相传值
2022-02-25 07:18:00