Python 中使用列表扩展的意外行为
我试图了解Python中的extend是如何工作的,但它并没有完全达到我的预期。例如:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6].extend(a)
>>> b
>>>
但我本来期望:
[4, 5, 6, 1, 2, 3]
为什么返回 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
extend()
方法追加到现有数组并返回None
。在你的例子中,你正在动态创建一个数组 -[4, 5, 6]
- 扩展它,然后丢弃它。变量b
最终返回值None
。The
extend()
method appends to the existing array and returnsNone
. In your case, you are creating an array —[4, 5, 6]
— on the fly, extending it and then discarding it. The variableb
ends up with the return value ofNone
.list
方法大部分就地操作,并返回None
。list
methods operate in-place for the most part, and returnNone
.其他人指出许多
list
方法,特别是那些改变列表的方法,返回None
而不是对列表的引用。他们这样做的原因是为了让您不会对是否制作了列表副本感到困惑。如果您可以编写a = b.extend([4, 5, 6])
,那么a
就是对与b
相同列表的引用?b
是否被语句修改了?通过返回None
而不是变异列表,这样的语句就变得毫无用处,你很快就会发现a
中没有你认为它包含的内容,并且你学习只写b.extend(...)
。因此,清晰度的缺乏就被消除了。Others have pointed out many
list
methods, particularly those that mutate the list, returnNone
rather than a reference to the list. The reason they do this is so that you don't get confused about whether a copy of the list is made. If you could writea = b.extend([4, 5, 6])
then isa
a reference to the same list asb
? Wasb
modified by the statement? By returningNone
instead of the mutated list, such a statement is made useless, you figure out quickly thata
doesn't have in it what you thought it did, and you learn to just writeb.extend(...)
instead. Thus the lack of clarity is removed.extend
扩展其操作数,但不返回值。如果你这样做了:那么你就会得到预期的结果。
extend
extends its operand, but doesn't return a value. If you had done:Then you would get the expected result.
我遇到了这个问题,虽然其他答案提供了正确的解释,但我喜欢的解决方案/解决方法不在这里。使用加法运算符将列表连接在一起并返回结果。就我而言,我将
color
作为 3 位数字列表,将opacity
作为浮点数进行记账,但库需要将颜色作为 4 位数字列表,将不透明度作为第 4 位数字。我不想命名一次性变量,因此这种语法适合我的需求:这会动态创建一个新的不透明度列表,并在连接后创建一个新列表,但这对于我的目的来说很好。我只是想要紧凑的语法来扩展带有浮点数的列表并返回结果列表而不影响原始列表或浮点数。
I had this problem and while the other answers provide correct explanations, the solution/workaround I liked isn't here. Using the addition operator will concatenate lists together and return the result. In my case I was bookkeeping
color
as a 3-digit list andopacity
as a float, but the library needed color as a 4 digit list with opacity as the 4th digit. I didn't want to name a throwaway variable, so this syntax suited my needs:This creates a new list for opacity on the fly and a new list after the concatenation, but that's fine for my purposes. I just wanted compact syntax for extending a list with a float and returning the resulting list without affecting the original list or float.