python:对我的复制变量的更改会影响原始变量 [英] python: changes to my copy variable affect the original variable
问题描述
我有一个列表,我创建了一个副本,以便在保留原始列表的同时进行一些操作.但是,当我将 copy_list
设置为 org_list
时,它们变成了相同的东西,如果我更改 copy_list
, org_list
> 也有变化.例如:
I've got a list that I create a copy of in order to do some manipulations while still keeping the original list. However, when I set copy_list
equal to org_list
, they become the same thing, and if I change copy_list
, org_list
changes too. For example:
org_list = ['y', 'c', 'gdp', 'cap']
copy_list = org_list
copy_list.append('hum')
print(copy_list)
print(org_list)
返回
['y', 'c', 'gdp', 'cap', 'hum']
['y', 'c', 'gdp', 'cap', 'hum']
我不太了解实际发生的事情,但看起来 org_list
实际上是将自己传递给 copy_list
以便它们实际上是同一件事.
I don't know too much about what is actually going on but it looks like org_list
is actually passing itself to copy_list
so that they are actually the same thing.
有没有办法制作一个独立的 org_list 副本,而不用做一些笨拙的事情:
Is there a way to make an independent copy of org_list without doing something clumsy like:
copy_list = []
for i in org_list:
copy_list.append(i)
我这么说是因为我对其他类型的变量也有同样的问题,例如熊猫数据框.
I say this because I have the same problem with other types of variables, for example a pandas dataframe.
推荐答案
那是因为在 python 设置变量中实际上设置了对变量的引用.几乎每个学习 Python 的人都会在某个时候遇到这个问题.解决方法很简单:复制列表:
That is because in python setting a variable actually sets a reference to the variable. Almost every person learning python encounters this at some point. The solution is simply to copy the list:
copy_list = org_list[:]
这篇关于python:对我的复制变量的更改会影响原始变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!