简体   繁体   English

列表中 extend() 和 + 之间的区别 - python

[英]Difference between extend() and + in lists - python

I want to know what is the exact difference between l1+l2 and l1.extend(l2) as it both concatenates the lists in python.我想知道 l1+l2 和 l1.extend(l2) 之间的确切区别是什么,因为它们都连接了 python 中的列表。

I have already went through the below post regarding the same question.我已经阅读了以下关于同一问题的帖子。

Concatenating two lists - difference between '+=' and extend() 连接两个列表 - '+=' 和 extend() 之间的区别

I clearly understand that extend() involves a function call and hence can be a bit more expensive.我清楚地知道 extend() 涉及 function 调用,因此可能会更贵一些。 And also l1+l2 option cannot be used for non-local variables.而且 l1+l2 选项不能用于非局部变量。

But in my case, I had a recursive code which eventually returns concatenation of two lists.但就我而言,我有一个递归代码,它最终返回两个列表的串联。 I used extend method l1.extend(l2).我使用扩展方法 l1.extend(l2)。 And i got the following errors.我收到以下错误。

n.netype' object is not iterable n.netype' object 不可迭代

object of type 'NoneType' has no len() “NoneType”类型的 object 没有 len()

But note that the list is not None or of NoneType.但请注意,该列表不是 None 或 NoneType。 I even tried printing the type(l1) and len(l1) and the type is list only.我什至尝试打印 type(l1) 和 len(l1) 并且类型仅为列表。

But one thing is that, if i replace extend method with l1 + l2, entire code works fine and i didn't get any error.但有一件事是,如果我用 l1 + l2 替换扩展方法,整个代码工作正常,我没有收到任何错误。

May I know why is this so?我可以知道为什么会这样吗? Any ideas/suggestions任何想法/建议

>>> print(l1.extend(l2))
None

l1.extend(l2) returns none while l1 has been updated.当 l1 已更新时, l1.extend(l2)不返回任何值。 The mistake (but without code we can't tell for sure) is probably that you need to assign l1.extend(l2) to a (new) variable again.错误(但没有代码我们无法确定)可能是您需要再次将l1.extend(l2)分配给(新)变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM