python中的列表分配 [英] List assignment in python

查看:42
本文介绍了python中的列表分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下代码,当我打印list1和list2时,它显示相同的元素,但是在将现有list1分配给list2之后我添加了9,所以它在list2中不应显示9.

I have a code like below,when i print the list1 and list2 it shows same elements but i have added the 9 after the assignment of existing list1 to list2 so it should not show 9 in list2.

list1=[1,2,3,4]
list2=list1
list1.insert(4,9)
print(list1)
print(list2)

请清除我的疑问.

推荐答案

在python中,变量名称是对基础变量的引用. list1 list2 都引用相同的列表,因此,当您在该列表中插入 9 时,都会看到两者的变化.您需要进行显式复制(使用 copy 模块,切片符号 list2 = list1 [:] 或其他方法),如果您希望它们与众不同.

In python, a variable name is a reference to the underlying variable. Both list1 and list2 refer to the same list, so when you insert 9 into that list, you see the change in both. You need to make an explicit copy (using the copy module, slice notation list2 = list1[:], or some other method) if you want them to be distinct.

这篇关于python中的列表分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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