简体   繁体   English

Python:对列表副本进行切片会在使用嵌套的for循环时影响原始的元组或列表

[英]Python: slicing a list copy affects the original tuple or list when using nested for loops

I'm having trouble changing any list copies of a list or tuple. 我在更改列表或元组的任何列表副本时遇到麻烦。 When using two nested For loops the tuple is changed, as below: 使用两个嵌套的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']]]

when only using one for loop is used, it works as I expect it to and only changes the copy: 当仅使用一个for循环时,它按我的预期工作并且仅更改副本:

for rowIndex, row in enumerate(testCopy):
    testCopy[rowIndex] = ['bar']

>>>([['foo'], ['foo']], [['foo'], ['foo']])
>>>[['bar'], ['bar']]

this happens regardless of if the original is a list or tuple or however the copy is formatted: 无论原始文件是列表还是元组,或者副本是否格式化,都会发生这种情况:

testCopy = testInput
testCopy = list(testInput)
testCopy = testInput[:]

Nested list copy with recursive function: This way the copy is a copy not related with the original 具有递归功能的嵌套列表副本:这样,副本就是与原始副本无关的副本

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM