【问题标题】:Python - List elements being overwritten somehowPython - 列表元素以某种方式被覆盖
【发布时间】:2016-02-01 04:27:10
【问题描述】:

我有一个递归函数,它试图找到添加到某个数字的数字组合。我将结果存储在一个名为 validCombinations

的列表中

代码:

sum = 4
digits = 2
currentDigit = digits
validCombinations = [] 

#recursion function to find combinations of numbers that add to the sum variable
def recursive(index):
    if 10 not in digitList:        
        if index >= 0:
            total = 0
            for n in digitList:
                total += n
            if total == sum:
                validCombinations.append(digitList)
            digitList[index] += 1
            recursive(index-1)
        else:
            recursive(currentDigit-1)

digitList = []

for n in range(digits,0,-1):
    for i in range(n):
        digitList.append(0)
    recursive(n-1)
    digitList = []
    currentDigit -= 1

print validCombinations

运行时会输出

[[9, 10], [10, 0]]

当我希望看到这个时

[[2, 2], [4]]

我已经单步执行了代码,它似乎以某种方式覆盖了列表中的元素,但是在我的代码中,我只使用 append() 方法与 validCombinations 进行交互,这应该只是将它添加到结束。

是我遗漏了什么还是递归导致了这个?

【问题讨论】:

标签: python list recursion append


【解决方案1】:

使用清单:

        if total == sum:
            validCombinations.append(list(digitList))

您必须获得 digitList 的副本,而不是 digitList。

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 2020-11-28
    • 2018-03-15
    • 2022-06-24
    • 2012-11-09
    • 2021-07-04
    • 2023-01-18
    • 2021-07-27
    • 1970-01-01
    相关资源
    最近更新 更多