Python 的插入返回 None? [英] Python's insert returning None?
本文介绍了Python 的插入返回 None?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
#!/usr/bin/python
numbers = [1, 2, 3, 5, 6, 7]
clean = numbers.insert(3, 'four')
print clean
# desire results [1, 2, 3, 'four', 5, 6, 7]
我得到无".我做错了什么?
I am getting "None". What am I doing wrong?
推荐答案
列表上的变异方法往往会返回 None
,不是 修改后的列表,如您所料 --此类方法通过就地更改列表来实现其效果,而不是通过构建和返回一个新列表.因此,print numbers
而不是 print clean
将显示更改后的列表.
Mutating-methods on lists tend to return None
, not the modified list as you expect -- such metods perform their effect by altering the list in-place, not by building and returning a new one. So, print numbers
instead of print clean
will show you the altered list.
如果您需要保持 numbers
不变,请先制作副本,然后更改副本:
If you need to keep numbers
intact, first you make a copy, then you alter the copy:
clean = list(numbers)
clean.insert(3, 'four')
这具有您似乎想要的整体效果:numbers
不变,clean
是更改后的列表.
this has the overall effect you appear to desire: numbers
is unchanged, clean
is the changed list.
这篇关于Python 的插入返回 None?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文