在 Python 中使用列表扩展的意外行为 [英] Unexpected Behavior of Extend with a list in Python
本文介绍了在 Python 中使用列表扩展的意外行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图了解扩展在 Python 中的工作原理,但它并没有完全按照我的预期工作.例如:
<预><代码>>>>a = [1, 2, 3]>>>b = [4, 5, 6].extend(a)>>>乙>>>但我会预料到:
[4, 5, 6, 1, 2, 3]
为什么返回 None 而不是扩展列表?
解决方案
extend()
方法追加到现有数组并返回 None
.在您的情况下,您正在动态创建一个数组 - [4, 5, 6]
- 对其进行扩展,然后将其丢弃.变量 b
以 None
的返回值结束.
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
>>>
But I would have expected:
[4, 5, 6, 1, 2, 3]
Why is that returning a None instead of extending the list?
解决方案
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屋!
查看全文