Python的插入返回无? [英] Python's insert returning None?

查看:106
本文介绍了Python的插入返回无?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/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的插入返回无?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆