【问题标题】:.pop() and .append() from one list affecting a different list?一个列表中的 .pop() 和 .append() 会影响另一个列表吗?
【发布时间】:2015-08-18 22:17:04
【问题描述】:

我正在用 Python 做一些组合学的东西,并得到一个奇怪的效果。我创建了几个列表,从一个列表中弹出,将结果附加到另一个列表中——但是 third 列表中已经存在的条目正在以某种方式被更改。

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[:]

【问题讨论】:

  • 不确定问题出在哪里,但 Python 通过引用传递列表。
  • 顺便说一句,你不需要fromListA.pop( len(fromListA) - 1 );你可以做fromListA.pop().pop() 默认为列表中的最后一项。
  • 啊,找到了。答案来了。
  • @Cyphase 哦!有两件事我不知道;谢谢!
  • 当然:)。已发布答案。

标签: python list append


【解决方案1】:

您的问题出在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弹出的事实。

【讨论】:

    【解决方案2】:

    问题已经解决了 -

    listB.append( cycle(fromListB) )
    

    如果 theList 的长度小于 3,则循环函数直接返回 'theList'。 fromListB 就是这种情况,因此 ListB 的第一个元素是对 fromListB 的引用,当你花费到 fromListB 时,它也反映了在 ListB 的第一个元素中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2020-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多