gpt4 book ai didi

python - .append() 不会将列表添加到列表列表中

转载 作者:行者123 更新时间:2023-12-01 05:16:31 24 4
gpt4 key购买 nike

我编写了一个脚本来查找按字典顺序排列的数字列表的所有排列。立即打印时输出是正确的,但如果我将其附加到列表中,输出会发生变化。在我的脚本的输出中,首先您会看到包含单个元素的列表,然后是我附加到该元素的列表,最后您会看到添加子列表后的完成列表:

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))

最佳答案

因为list中的列表实际上是一个引用,在使用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]]

应该是你想要的:)

关于python - .append() 不会将列表添加到列表列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23085407/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com