我正在用 Python 做一些组合运算,并得到了奇怪的效果。我创建了几个列表,从一个列表中弹出,将结果 append 到另一个列表中,但第三列表中已经存在的条目正在以某种方式被更改。
def cycle( theList ):
cycleList = []
if len(theList) < 3:
return theList
for ii in range( len(theList) - 2 ):
cycleList.append([
theList[ii],
theList[ii + 1],
theList[ii + 2] ])
return cycleList
Combos = [[1, 2, 3, 4, 5], [1, 3, 2, 4, 5]]
for combo in Combos:
listA = []
listB = []
fromListA = [x for x in combo]
fromListB = [fromListA[0]]
listA.append( cycle(fromListA) )
listB.append( cycle(fromListB) )
for jj in range(1, len(combo) - 1):
print("List B's first entry: " + str(listB[0]) )
fromListB.append( fromListA.pop( len(fromListA) - 1 ))
print("List B's first entry: " + str(listB[0]) )
break
break
这是输出:
>>> execfile('test.py')
List B's first entry: [1]
List B's first entry: [1, 5]
>>>
我最近一直在学习 C++,所以我想寻找一个奇怪的引用资料或其他东西......
...但这是Python。
编辑:热死了!这是一个引用问题。
要复制列表,可以使用
listA = list(listB)
或
listA = listB[:]
最佳答案
您的问题出在cycle()
函数中。
def cycle( theList ):
cycleList = []
if len(theList) < 3: # <<< PROBLEM IS HERE <<<<<
return theList # <<<<< PROBLEM IS HERE <<<<<
for ii in range( len(theList) - 2 ):
cycleList.append([
theList[ii],
theList[ii + 1],
theList[ii + 2] ])
return cycleList
当您在外部 for
循环中执行 fromListB = [fromListA[0]]
时,fromListB
的长度为 1。然后,当您执行 listB.append(cycle(fromListB) )
时,cycle(fromListB)
最终返回您传入的相同列表,因此 listB[0]
现在指向与 fromListB
相同的列表。
现在,当您在内部 for
循环中执行 fromListB.append( fromListA.pop( len(fromListA) - 1 ))
时,您正在修改相同的内容listB[0]
指向的列表。
顺便说一句,相关位是 fromListB.append('ANYTHING')
,而不是您从 fromListA
弹出的事实。
关于python - 一个列表中的 .pop() 和 .append() 会影响另一列表吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32083491/