使用循环时,列表行为非常奇怪

2024-09-28 22:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列表,开头是

value=[1,2,3]
out_list=[value]

while(i<2*len(nums)):
         
        temp_value=temp[locator]
        temp[locator]=temp[locator+1]
        temp[locator+1]=temp_value
        print(temp, end="   ")
        output_list+=[temp]
        print(output_list)
        i+=1

然后我看一下我用temp得到的值是一些正常值,如图所示:

[1, 3, 2] 
[3, 2, 1]
[3, 1, 2]
[2, 3, 1]
[2, 1, 3]

这应该意味着我的输出列表也很好,对吗?不,这是我的最终输出

[[1, 3, 2], [1, 3, 2], [1, 3, 2]]
[[1, 3, 2], [1, 3, 2], [1, 3, 2], [3, 2, 1]]
[[1, 3, 2], [1, 3, 2], [1, 3, 2], [3, 1, 2], [3, 1, 2]]
[[1, 3, 2], [1, 3, 2], [1, 3, 2], [3, 1, 2], [3, 1, 2], [2, 3, 1]]
[[1, 3, 2], [1, 3, 2], [1, 3, 2], [3, 1, 2], [3, 1, 2], [2, 1, 3], [2, 1, 3]]

Tags: 列表outputlenvalueouttemplistend
2条回答

你只想让名单上的人加入,对吗

比如:

a=[1,2,3]
b=[3,2,1]
print (a+b)
[1,2,3,3,2,1]

如果是这种情况,请从[temp]中删除[]

output_list+=temp

更新: 试试这个

from itertools import permutations 
comb = permutations([1, 2, 3], 3)
result=[]
for i in comb: 
    result+=[list(i)]
print(result)

我发布了一个回溯解决方案-因为你的标签中有回溯。 这将为您提供列表的所有排列->;嵌套列表作为输出

def permute(nums):
    
    outputList = []
    set_ = set()
    
    def helper(l, count = 0):
        if count == len(nums):
            outputList.append(l)
        else:
            for number in nums:
                if number not in set_:
                    set_.add(number)
                    helper(l + [number], count + 1)
                    set_.remove(number)
    helper([])
    return outputList

permute([1,2,3])将产生

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]

相关问题 更多 >