追加列表给打印结果给出了不同的结果

时间:2019-01-27 15:04:08

标签: python python-3.x

我的python代码只是尝试打印给定列表(我的代码中为num)的所有排列。这是我的代码

#!/usr/bin/python3    

        def permutation(list_num, checked_length, length):
            if checked_length == length - 1:
                print(list_num)
            else:
                for i in range(checked_length, length):
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]
                    permutation(list_num, checked_length + 1, length)
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]


        num = [1, 2, 3]
        permutation(num, 0, len(num))

它给出了我想要的结果

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

但是当我尝试改变一点时。我希望该代码的输出存储在Answer_list中。我得到了这个意外的结果:

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

这是我的代码得到的结果:

        #!/usr/bin/python3
    Answer_list = []
    def permutation(list_num, checked_length, length):
            if checked_length == length - 1:
                Answer_list.append(list_num) # change here
            else:
                for i in range(checked_length, length):
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]
                    permutation(list_num, checked_length + 1, length)
                    list_num[i], list_num[checked_length] = list_num[checked_length], list_num[i]


num = [1, 2, 3]
permutation(num, 0, len(num))
print(Answer_list)

0 个答案:

没有答案