【发布时间】: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 哦!有两件事我不知道;谢谢!
-
当然:)。已发布答案。