29

我正在尝试在 Python 中实现一种算法来生成列表的所有排列。但是我在我的 for 循环中我希望保持原始前缀和剩余列表完好无损,因此我试图使用 newprefix 和 newrest 制作这些列表的副本,但是在每次迭代时打印变量 rest 时,我看到即使可变休息正在被修改!如何在 Python 中制作列表的浅表副本?或者我尝试的逻辑还有其他问题吗?

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'])
4

2 回答 2

44

要制作浅拷贝,您可以对列表进行切片:

newprefix = prefix[:]

或者将其传递给list构造函数:

newprefix = list(prefix)

另外,我认为您可以稍微简化代码:

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'])
于 2013-04-29T02:26:59.653 回答
16
import copy

a = [somestuff]
b = copy.copy(a) # Shallow copy here.
c = copy.deepcopy(a) # Deep copy here.

复制模块值得了解。 https://docs.python.org/3/library/copy.html

(Python 2) http://docs.python.org/2/library/copy.html

于 2013-04-29T02:27:47.233 回答