谈谈 Python 中的连接符（+、+=）

2016/05/26 12:37

a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
c = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

for item in (a, b, c):
item += [0] * (10 - len(item))

print a
print b
print c


[1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
[5, 6, 7, 8, 9, 0, 0, 0, 0, 0]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]


a = [1, 2, 3, 4]
b = [5, 6, 7, 8, 9]
c = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

for item in (a, b, c):
item = [0] * (10 - len(item)) + item

print a
print b
print c


[1, 2, 3, 4]
[5, 6, 7, 8, 9]
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20]


>>> l = [1, 2, 3, 4, 5]
>>> l = [0]*5 + l
>>> l
[0, 0, 0, 0, 0, 1, 2, 3, 4, 5]


>>> l = [1, 2, 3, 4, 5]
>>> id(l)
139935500860952
>>> l = [0]*5 + l
>>> l
[0, 0, 0, 0, 0, 1, 2, 3, 4, 5]
>>> id(l)
139935500783272


>>> l = [1, 2, 3, 4, 5]
>>> id(l)
139935500861024
>>> l += [0]*5
>>> l
[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
>>> id(l)
139935500861024


>>> t = (1, 2, 3, 4, 5)
>>> id(t)
139935501840656
>>> t += (0,)*5
>>> t
(1, 2, 3, 4, 5, 0, 0, 0, 0, 0)
>>> id(t)
139935502151336


>>> t = (1, 2, 3, 4, 5)
>>> id(t)
139935501081200
>>> t = (0,)*5 + t
>>> t
(0, 0, 0, 0, 0, 1, 2, 3, 4, 5)
>>> id(t)
139935502151336


>>> s = "hello"
>>> id(s)
139935500909712
>>> s += "world"
>>> s
'helloworld'
>>> id(s)
139935500909664


• 对于可变类型：

• +： 代表连接操作，其结果会创建一个新的对象。
• +=： 代表追加操作，即 in-place 操作，在原地把另一个对象的内容追加到对象中。
• 对于不可变类型： ++= 都代表连接或求和操作，两者没有什么区别，其操作的结果都会产生一个新的对象。

>>> a = [1, 2, 3, 4]
>>> t = a
>>> id(a)
139712695835400
>>> id(t)
139712695835400
>>> t += [0]*6
>>> t
[1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
>>> id(t)
139712695835400
>>> id(a)
139712695835400
>>> a
[1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
>>>
>>>
>>> a = [1, 2, 3, 4]
>>> t = a
>>> id(a)
139712695835464
>>> id(t)
139712695835464
>>> t = [0]*6 + t
>>> t
[0, 0, 0, 0, 0, 0, 1, 2, 3, 4]
>>> a
[1, 2, 3, 4]
>>> id(a)
139712695835464
>>> id(t)
139712695835400


0
3 收藏

0 评论
3 收藏
0