为什么list(my_list)修改对象? [英] Why does list(my_list) modify the object?

查看:87
本文介绍了为什么list(my_list)修改对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发生了这种特殊行为:

I happened on this peculiar behaviour accidentally:

>>> a = []
>>> a[:] = ['potato', a]
>>> print a
['potato', [...]]
>>> print list(a)
['potato', ['potato', [...]]]

通过什么机制调用list(a)会在其自身的字符串表示形式中展开一级递归?

By what mechanism does calling list(a) unroll one level of recursion in the string representation of itself?

推荐答案

list()进行浅表复制.外部列表与其包含的列表不再是同一对象.它会按您期望的那样打印.

list() makes a shallow copy. The outer list is no longer the same object as the list it contains. It is printed as you would expect.

这篇关于为什么list(my_list)修改对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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