[英]Python: slicing a list copy affects the original tuple or list when using nested for loops
我在更改列表或元組的任何列表副本時遇到麻煩。 使用兩個嵌套的For循環時,將更改元組,如下所示:
testInput = ( ['foo','foo',], ['foo','foo'] )
testCopy = list(testInput)
for rowIndex, row in enumerate(testCopy):
for columnIndex, column in enumerate(row):
testCopy[rowIndex][columnIndex] = ['bar']
print(testInput)
print(testCopy)
>>>([['bar'], ['bar']], [['bar'], ['bar']])
>>>[[['bar'], ['bar']], [['bar'], ['bar']]]
當僅使用一個for循環時,它按我的預期工作並且僅更改副本:
for rowIndex, row in enumerate(testCopy):
testCopy[rowIndex] = ['bar']
>>>([['foo'], ['foo']], [['foo'], ['foo']])
>>>[['bar'], ['bar']]
無論原始文件是列表還是元組,或者副本是否格式化,都會發生這種情況:
testCopy = testInput
testCopy = list(testInput)
testCopy = testInput[:]
具有遞歸功能的嵌套列表副本:這樣,副本就是與原始副本無關的副本
def copyList(yourList):
yourCopiedList=[]
for listElement in yourList:
if type(listElement)==list:
yourCopiedList.append(copyList(listElement.copy()))
else:
yourCopiedList.append(listElement)
return yourCopiedList
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.