【问题标题】:Cannot copy a local variable to result Array无法将局部变量复制到结果数组
【发布时间】:2017-02-13 20:29:45
【问题描述】:

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

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

【问题讨论】:

  • 试试result.append(tempList[:])
  • 谢谢@jonrsharpe

标签: python permutation backtracking


【解决方案1】:

内部列表为空的原因是您正在使用tempList.pop()修改原始临时列表

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

import copy

改变

result.append(tempList)

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

【讨论】:

    猜你喜欢
    • 2022-12-06
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多