我编写了一个脚本,用于按字典顺序查找数字列表的所有排列。立即打印时输出正确,但如果我将其附加到列表中则会更改。在我的脚本输出中,首先看到包含单个元素的列表,然后是我追加到该元素的列表,最后在添加子列表后看到完成的列表:
Find all permutations of 1 -> x. x = ? 3
[[1, 2, 3]]
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 3, 2], [2, 3, 1], [2, 3, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
如您所见,初始[1,2,3]列表在最终输出中甚至不是。以下是我的代码。有人能告诉我到底发生了什么事吗?
permutation_range = int(input('Find all permutations of 1 -> x. x = ? '))
def permutation_finder(x):
permutation = list(range(1, 1+x))
rev_permutation = permutation[::-1]
permutation_list = [permutation]
print(permutation_list, '\n\n') #bugcheck print
while permutation != rev_permutation:
permutation, index_k = step_1(permutation)
permutation, index_k, index_l = step_2(permutation, index_k)
permutation, index_k = step_3(permutation, index_k, index_l)
permutation = step_4(permutation, index_k)
permutation_list.append(permutation)
print(permutation) #bugcheck print
return permutation_list
def step_1(permutation):
for val in permutation[:-1][::-1]:
index_k = permutation.index(val)
if val < permutation[index_k+1]:
return permutation, index_k
def step_2(permutation, index_k):
for val in permutation[index_k+1:][::-1]:
if val > permutation[index_k]:
index_l = permutation.index(val)
return permutation, index_k, index_l
def step_3(permutation, index_k, index_l):
a_k, a_l = permutation[index_k], permutation[index_l]
permutation[index_k], permutation[index_l] = a_l, a_k
return permutation, index_k
def step_4(permutation, index_k):
front = permutation[:index_k+1]
back = permutation[index_k+1:]
back.reverse()
permutation = front + back
return permutation
print('\n\n', permutation_finder(permutation_range))
答案 0 :(得分:2)
因为列表中的列表实际上是一个引用,而不是在使用append()
时转换为值。因此,当您之后编辑列表时,之前添加的列表也会更改。
在追加之前添加[:]
来复制列表可以修复它:
def permutation_finder(x):
permutation = list(range(1, 1+x))
rev_permutation = permutation[::-1]
permutation_list = [permutation[:]]
print(permutation_list, '\n\n') #bugcheck print
while permutation != rev_permutation:
permutation, index_k = step_1(permutation)
permutation, index_k, index_l = step_2(permutation, index_k)
permutation, index_k = step_3(permutation, index_k, index_l)
permutation = step_4(permutation, index_k)
permutation_list.append(permutation[:])
print(permutation) #bugcheck print
return permutation_list
(注意[:]
部分)
改变之后,我可以得到:
$ python permutation.py
Find all permutations of 1 -> x. x = ? 3
[[1, 2, 3]]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
应该是你想要的:)