Python 列表:为什么在连接操作后会创建新的列表对象? [英] Python Lists : Why new list object gets created after concatenation operation?

查看:55
本文介绍了Python 列表:为什么在连接操作后会创建新的列表对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Python 5E 书中关于列表的主题.我注意到如果我们在列表上进行连接,它会创建新对象.Extend 方法不创建新对象,即就地更改.在串联的情况下实际会发生什么?

I was going through the topic about list in Learning Python 5E book. I notice that if we do concatenation on list, it creates new object. Extend method do not create new object i.e. In place change. What actually happens in case of Concatenation?

例如

l = [1,2,3,4]
m = l
l = l + [5,6]
print l,m

#output
([1,2,3,4,5,6], [1,2,3,4])

如果我按如下方式使用增强分配,

And if I use Augmented assignment as follows,

l = [1,2,3,4]
m = l
l += [5,6]
print l,m

#output
([1,2,3,4,5,6], [1,2,3,4,5,6])

在这两种操作的情况下,后台发生了什么?

What is happening in background in case of both operations?

推荐答案

这里使用了两种方法:__add____iadd__.l + [5, 6]l.__add__([5, 6]) 的快捷方式.l__add__ 方法返回与其他内容相加的结果.因此,l = l + [5, 6] 是将 l 重新赋值给 l[5, 6].它不会影响 m 因为您不是在更改对象,而是在重新定义名称.l += [5, 6]l.__iadd__([5, 6]) 的快捷方式.在这种情况下,__iadd__ 更改列表.由于 m 指向同一个对象,所以 m 也会受到影响.

There are two methods being used there: __add__ and __iadd__. l + [5, 6] is a shortcut for l.__add__([5, 6]). l's __add__ method returns the result of addition to something else. Therefore, l = l + [5, 6] is reassigning l to the addition of l and [5, 6]. It doesn't affect m because you aren't changing the object, you are redefining the name. l += [5, 6] is a shortcut for l.__iadd__([5, 6]). In this case, __iadd__ changes the list. Since m refers to the same object, m is also affected.

Edit:如果 __iadd__ 未实现,例如使用像 tuplestr 这样的不可变类型,则Python 使用 __add__ 代替.例如,x += y 将转换为 x = x + y.另外,在x + y中,如果x没有实现__add__,那么y.__radd__(x),如果可用,将被使用.因此x += y 可能实际上是x = y.__radd__(x)在后台.

Edit: If __iadd__ is not implemented, for example with immutable types like tuple and str, then Python uses __add__ instead. For example, x += y would be converted to x = x + y. Also, in x + y if x does not implement __add__, then y.__radd__(x), if available, will be used instead. Therefore x += y could actually be x = y.__radd__(x) in the background.

这篇关于Python 列表:为什么在连接操作后会创建新的列表对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆