问题描述
假设我有这些任务:
points = []
point = (1, 2)
怎么办?
points += point
它完全可以正常工作,并给我分= [1,2].但是,如果我做类似的事情:
points = points + point
它给了我TypeError:只能串联列表(而不是元组")到列表.这些陈述不是一回事吗?
区别在于,list +=
等效于list.extend()
,它接受任何可迭代并扩展了列表,它作为元组是可迭代的. (并就地扩展列表).
另一方面,第二个方法为points
分配了一个新列表,并尝试将一个列表连接到一个元组,但由于尚不清楚预期的结果是什么(列表或元组?),所以没有这样做. /p>
Let's say I have these assignments:
points = []
point = (1, 2)
How come when I do this:
points += point
It works completely fine, and gives me points = [1, 2].However, If I do something like:
points = points + point
It gives me a TypeError: can only concatenate list (not "tuple") to list.Aren't these statements the same thing, though?
The difference, is that list +=
is equivalent to list.extend()
, which takes any iterable and extends the list, it works as a tuple is an iterable. (And extends the list in-place).
On the other hand, the second assigns a new list to points
, and attempts to concatenate a list to a tuple, which isn't done as it's unclear what the expected results is (list or tuple?).
这篇关于列表+ =元组vs列表=列表+元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!