在Python中使用列表进行扩展的意外行为 [英] Unexpected Behavior of Extend with a list in Python
本文介绍了在Python中使用列表进行扩展的意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图了解扩展在Python中的工作方式,但并没有达到我的期望.例如:
I am trying to understand how extend works in Python and it is not quite doing what I would expect. For instance:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6].extend(a)
>>> b
>>>
但我本来期望:
[4, 5, 6, 1, 2, 3]
为什么返回None而不是扩展列表?
Why is that returning a None instead of extending the list?
推荐答案
extend()
方法将追加到现有数组并返回None
.在您的情况下,您正在动态创建一个数组-[4, 5, 6]
-对其进行扩展,然后将其丢弃.变量b
以返回值None
结尾.
The extend()
method appends to the existing array and returns None
. In your case, you are creating an array — [4, 5, 6]
— on the fly, extending it and then discarding it. The variable b
ends up with the return value of None
.
这篇关于在Python中使用列表进行扩展的意外行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文