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

标签 python list append

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

相关文章:

python 3.3 : Invalid Syntax error in line 7 of the below code

c - 链表无法连接节点

list - 如何将列表转换为 Erlang 中的函数参数?

matlab - 如何更改 Matlab 图中线条的顺序?

javascript - 无法获得 ajax 响应以使用 python 代码放置好

python - 系列的 Groupby 和 max

计算 Pandas 数据框中条纹的Pythonic方法

python - Pydot - 将节点存储在列表中 - 不可散列类型 : 'list' error

r - 在摊余常数时间内将一个对象追加到 R 中的列表中,O(1)?

javascript - css 未应用于使用 jQuery .append() 创建的 html 元素