我写了这个剧本:
soilMod = ['ptaaco']
n = 2
soilModSplit = [soilMod[i:i+n] for i in range(0, len(soilMod), n)] # This returns ['pt', 'aa', 'co']
alphaTest = soilModSplit # I want to maintain the original list built before I remove items below. This returns ['pt', 'aa', 'co'] as well
if 'pt' in soilModSplit:
soilModSplit.remove('pt')
print soilModList # This returns ['aa', 'co']
print alphaTest # This also returns ['aa', 'co'] It's missing the original ['pt', 'aa', 'co'] and I didn't ask the script to remove it from this particular list.
出于某种原因,当我从soilModSplit中删除项目('pt')时,它也会从alphaTest中删除该项目。这是预期的结果吗?似乎构建在soilModSplit上的任何变量(在这种情况下,alphaTest)都依赖于对soilModSplit采取的任何操作。也许我做错了什么?有办法解决这个问题吗?
谢谢, 麦克
答案 0 :(得分:2)
alphaTest = soilModSplit
alphatest
只是绑定到soilModSplit
的同一列表的另一个名称。制作浅色副本:
alphaTest = list(soilModSplit )
答案 1 :(得分:1)
执行alphaTest = soilModSplit
时,您没有创建副本。您只有两个引用相同列表的名称。如果要保存副本,请执行alphaTest = list(soilModSplit)
。