Why a local variable is updating itself?
本问题已经有最佳答案,请猛点这里访问。
我有以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | file = open('MyCSV.csv') # this read the Headers name reader = csv.reader(file) Data = next(reader,None) Data = Data[1:] DataTmp = Data for item in DataM: # DataM is a list with one element from Data Data.remove(item) #remove one item # print(len(Data)) print(len(DataTmp)) |
因此,我打开
然后,我从
现在,我预计
谢谢你的帮助!
重要的改变是
1 | import copy |
和
1 | DataTmp = copy.copy(Data) # Use this instead of direct assignment. |
而不是
1 | DataTmp = Data |
使用下面的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import copy file = open('MyCSV.csv') # this read the Headers name reader = csv.reader(file) Data = next(reader,None) Data = Data[1:] # DataTmp = Data DataTmp = copy.copy(Data) # Use this instead of direct assignment. for item in DataM: # DataM is a list with one element from Data Data.remove(item) #remove one item # print(len(Data)) print(len(DataTmp)) |