如何在 Python 中制作列表的浅拷贝 [英] How to make a shallow copy of a list in Python
问题描述
我正在尝试在 Python 中实现一种算法来生成列表的所有排列.但是我在我的 for 循环中,我希望保持原始前缀和其余列表完好无损,因此我试图使用 newprefix 和 newrest 制作这些列表的副本,但是在每次迭代时打印变量 rest 时,我看到即使是可变休息正在被修改!如何在 Python 中制作列表的浅拷贝?或者我尝试的逻辑还有其他问题吗?
I am trying to implement an algorithm in Python to generate all Permutations of a list. But I In my for loop I wish to keep the original prefix and rest lists intact, and therefore I am trying to make a copy of those lists using newprefix and newrest, however on printing the variable rest at each iteration, I see that even the variable rest is getting modified! How can I make a shallow copy of the list in Python? Or is there another issue with my attempted logic?
def perm(prefix, rest):
if len(rest) == 0:
print prefix
for i in range(len(rest)):
#prints in the for loop are just for debugging
print "rest:", rest
print "i=", i
newprefix = prefix
newprefix.append(rest[i])
newrest = rest
newrest.pop(i)
print "old pre : ", prefix
print "newpre=", newprefix
print "newrest=", newrest
perm(newprefix, newrest)
perm([], ['a','b','c'])
推荐答案
要制作浅拷贝,可以将列表切片:
To make a shallow copy, you can slice the list:
newprefix = prefix[:]
或者将其传递到list
构造函数中:
Or pass it into the list
constructor:
newprefix = list(prefix)
另外,我认为您可以稍微简化一下代码:
Also, I think you can simplify your code a little:
def perm(prefix, rest):
print prefix, rest
for i in range(len(rest)):
perm(prefix + [rest[i]], rest[:i] + rest[i + 1:])
perm([], ['a','b','c'])
这篇关于如何在 Python 中制作列表的浅拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!