美文网首页
Python中 i = i + 1 与 i += 1的区别

Python中 i = i + 1 与 i += 1的区别

作者: ukeyim | 来源:发表于2017-02-27 22:54 被阅读0次

今天朋友碰到了问题

l = []
lst = []
lst.append(l)
l += [1]
# lst = [1]
l = l + [2]
# lst = [1]
l += [3]
# lst = [3]

为什么lst里面的l值通过 l += [1]可以改变, 而l = l + [1]就没法影响lst里面的值呢? +

解决

+= 是对原本的实例做加1运算, l = l + [1]是对l + [1]之后重新把值赋给叫l的变量(和原来的l不同)。

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.

Just for completeness:

x += y is not always doing an in-place operation, there are (at least) three exceptions:

If x doesn't implement an iadd method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int.

If iadd returns NotImplemented, Python falls back to x = x + y.

The iadd method could theoretically be implemented to not work in place. It'd be really weird to do that, though.

转自:
What is the difference between i = i + 1 and i += 1 in a 'for' loop? [duplicate]

相关文章

网友评论

      本文标题:Python中 i = i + 1 与 i += 1的区别

      本文链接:https://www.haomeiwen.com/subject/lemtgttx.html