无法将局部变量复制到结果数组



它打印正确的值,但不在结果数组中存储任何内容。这是我的代码:

def backtrack(result, nums, tempList):
    if len(tempList) == len(nums):
        result.append(tempList)
    else:
        for i in range(0, len(nums)):
            if not tempList.count(nums[i]):
                tempList.append(nums[i])
                backtrack(result, nums, tempList)
                tempList.pop()
nums = [1, 2, 3]
result = []
backtrack(result, nums, [])
print result

你得到空的内部列表的原因是你正在修改原始的临时列表tempList.pop()

您可以做的是在将tempList附加到result之前复制它:

import copy

改变

result.append(tempList)

mycopy = copy.deepcopy(tempList)
result.append(mycopy)

最新更新