【问题标题】:Python: slicing a list copy affects the original tuple or list when using nested for loopsPython:使用嵌套 for 循环时,对列表副本进行切片会影响原始元组或列表
【发布时间】:2018-05-18 12:46:49
【问题描述】:

我无法更改列表或元组的任何列表副本。当使用两个嵌套的 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[:]

【问题讨论】:

  • testCopy = list(testInput) 是浅拷贝,也有点不是拷贝,因为testInput 是一个元组,而不是一个列表。
  • 啊我明白了。它只是复制数据的外层,所以['data'] 是一个引用非唯一'data' 的唯一列表。谢谢!

标签: python-3.x list tuples slice


【解决方案1】:

具有递归函数的嵌套列表副本: 这样副本是与原件无关的副本

def copyList(yourList):   
    yourCopiedList=[]   
    for listElement in yourList:
    if type(listElement)==list:
      yourCopiedList.append(copyList(listElement.copy()))
    else:
      yourCopiedList.append(listElement)   
    return yourCopiedList

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-01-29
  • 2019-03-27
  • 1970-01-01
  • 1970-01-01
  • 2015-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多