【问题标题】:What is the difference between these two ways of appending tuples to a list [duplicate]这两种将元组附加到列表的方法有什么区别[重复]
【发布时间】:2018-10-04 13:31:34
【问题描述】:

我有以下代码中断:

l = []
tup = ('a', 'b')
l = l + tup

给出以下错误

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "tuple") to list

但下面的代码运行

l = []
tup = ('a','b')
l += tup

没有任何错误。

我一直认为 l+= 和 l = l + 是一样的

这里发生了什么事?

【问题讨论】:

  • 第一个操作失败,因为它首先执行l+tup,它调用了不支持的__add__,后者调用了__iadd__,它的实现允许这样做,所以它们的实现不一定相同

标签: python


【解决方案1】:

问题是l = l + 调用list__add__ 方法,而l += 调用__iadd__ 方法,这是就地加法(相当于调用extend 方法)。

【讨论】:

    猜你喜欢
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    • 2019-03-31
    • 1970-01-01
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多