在python中, a + = b的行为并不总是与a = a + b相同, 相同的操作数在不同条件下可能会给出不同的结果。
考虑以下示例以进行列表操作:
例子1
list1 = [ 5 , 4 , 3 , 2 , 1 ]
list2 = list1
list1 + = [ 1 , 2 , 3 , 4 ]
print (list1)
print (list2)
输出如下:
[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1, 1, 2, 3, 4]

例子2
list1 = [ 5 , 4 , 3 , 2 , 1 ]
list2 = list1
list1 = list1 + [ 1 , 2 , 3 , 4 ]
# Contents of list1 are same as above
# program, but contents of list2 are
# different.
print (list1)
print (list2)
输出如下:
[5, 4, 3, 2, 1, 1, 2, 3, 4]
[5, 4, 3, 2, 1]

- 表达list1 + = [1、2、3、4]就地修改列表, 意味着它扩展了列表, 以使” list1″和” list2″仍具有对同一列表的引用。
- 表达list1 = list1 + [1、2、3、4]创建一个新列表, 并将” list1″引用更改为该新列表, ” list2″仍引用旧列表。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。
来源:
https://www.srcmini02.com/70560.html