gpt4 book ai didi

python - 一个列表中的 .pop() 和 .append() 影响另一个列表?

转载 作者:太空宇宙 更新时间:2023-11-04 01:02:40 24 4
gpt4 key购买 nike

我正在用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com