【发布时间】:2019-11-23 08:08:03
【问题描述】:
最近,我注意到连接列表时出现不一致。
因此,如果我使用 + 运算符,它不会将列表与任何不同类型的对象连接起来。例如,
l = [1,2,3]
l = l + (4,5) #TypeError: can only concatenate list (not "tuple") to list
但是,如果我使用 += 运算符,它会忽略对象的类型。例如,
l = [1,2,3]
l += "he" #Here, l becomes [1, 2, 3,"h", "e"]
l += (56, 67) #Here, l becomes [1, 2, 3,"h", "e", 56, 67]
那么,仅仅是语言的语义还是其他原因?
【问题讨论】:
-
如果您将
+与不同类型的操作数一起使用,那么您期望的结果是什么类型存在歧义。使用+=,暗示左操作数确定结果的类型。 -
+=列表或多或少相当于list.extend()
标签: python python-3.x list concatenation