Python列表扩展和变量分配 [英] Python list extension and variable assignment

查看:73
本文介绍了Python列表扩展和变量分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图扩展列表,但对结果返回值为None感到困惑.我尝试过的是这样:

I tried to extend a list and was puzzled by having the result return with the value None. What I tried was this:

>>> a = [1,2]  
>>> b = [3,4]  
>>> a = a.extend(b)  
>>> print a  

None

我终于意识到问题出在最后是对"a"的多余分配.这样就可以了:

I finally realized that the problem was the redundant assignment to 'a' at the end. So this works:

>>> a = [1,2]  
>>> b = [3,4]  
>>> a.extend(b)  
>>> print a  

[1,2,3,4]

我不明白的是为什么的第一个版本不起作用.分配给"a"是多余的,但是为什么会中断操作?

What I don't understand is why the first version didn't work. The assignment to 'a' was redundant, but why did it break the operation?

推荐答案

由于您注意到,extend的返回值为None.这在Python标准库中很常见;破坏性操作会返回None,即没有值,因此您不会像对待纯函数那样使用它们.阅读圭多岛对此设计选择的说明.

Because, as you noticed, the return value of extend is None. This is common in the Python standard library; destructive operations return None, i.e. no value, so you won't be tempted to use them as if they were pure functions. Read Guido's explanation of this design choice.

例如,列表上的sort方法也返回None,而非破坏性sorted函数返回一个值.

E.g., the sort method on lists returns None as well, while the non-destructive sorted function returns a value.

这篇关于Python列表扩展和变量分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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