这是一个算法,用于记下列表P的一些排列,并且它做得很好,但是......
def p():
global P
P = ['a', 'b', 'c', 'd']
perm(4)
per = []
def perm(k):
global P
if k==1:
print(P)
per.append(P)
else:
for i in range(k):
P[i], P[k-1] = P[k-1], P[i]
perm(k-1)
P[i], P[k-1] = P[k-1], P[i]
当我希望它将排列添加到全局列表(对于程序的其余部分是必需的)时,存在问题。它仍会打印所有排列
['b', 'c', 'd', 'a']
['b', 'c', 'd', 'a']
['d', 'b', 'c', 'a']
['d', 'b', 'c', 'a']
['b', 'd', 'c', 'a']
['b', 'd', 'c', 'a']
['a', 'c', 'b', 'd']
['a', 'c', 'b', 'd']
['b', 'a', 'c', 'd']
['b', 'a', 'c', 'd']
['a', 'b', 'c', 'd']
['a', 'b', 'c', 'd']
['b', 'd', 'a', 'c']
['b', 'd', 'a', 'c']
['a', 'b', 'd', 'c']
['a', 'b', 'd', 'c']
['b', 'a', 'd', 'c']
['b', 'a', 'd', 'c']
['a', 'd', 'b', 'c']
['a', 'd', 'b', 'c']
['b', 'a', 'd', 'c']
['b', 'a', 'd', 'c']
['a', 'b', 'd', 'c']
['a', 'b', 'd', 'c']
但是当我检查列表时,它会填充默认设置
[['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b',
'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'],
['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b',
'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'],
['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b',
'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'],
['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c'], ['a', 'b', 'd', 'c']]
你能帮我解决一下实际问题吗?
答案 0 :(得分:0)
使用
per.append(P[:])
复制列表。您正在附加对列表的引用,并且始终是相同的数据。您的per
反复包含相同的引用。
cdarke评论评论:
切片列表会打开一个浅表副本 - 如果你有包含其他引用的列表(内部列表),它只会复制引用,并且你对内部列表有同样的问题 - 你将不得不求助于复制。在这种情况下进行深度检查。
示例:
innerlist = [1,2,3]
l2 = [innerlist, 5, 6]
l3 = l2[:]
print(l2) # orig
print(l3) # the shallow copy
l3[2] = "changed" # l2[2] is unchanged
print(l2)
print(l3)
innerlist[2] = 999 # both (l2 and l3) will reflect this change in the innerlist
print(l2)
print(l3)
输出:
[[1, 2, 3], 5, 6] # l2
[[1, 2, 3], 5, 6] # l3
[[1, 2, 3], 5, 6] # l2 unchanged by l3[2]='changed'
[[1, 2, 3], 5, 'changed'] # l3 changed by -"-
[[1, 2, 999], 5, 6] # l2 and l3 affected by change in innerlist
[[1, 2, 999], 5, 'changed']
答案 1 :(得分:0)
使用内置permutations:
可能更方便from itertools import permutations
arr = [1, 2, 3]
list(permutations(arr))
> [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
答案 2 :(得分:0)
尝试使用内置的itertools link。
import itertools
P = [letter for letter in "abcd"]
def perm(permutate_this):
return list(itertools.permutations(permutate_this))
print(perm(P))