python递归追加到列表

标签 python list recursion append

我试图在每次当前更改时将当前追加到 master 中。我使用列表失败。我已经能够修改字符串并 append 不同的字符串来掌握,但如果我可以使用列表,那就容易多了。

master = []

def recur(count,current):
    count = count + 1
    if (count == 5):
        return
    current.append(1)
    master.append(current)
    recur(count,current)


recur(0,[])

print(master)
# out put
# [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]

# what I expected
# [[1], [1,1], [1,1,1], [1,1,1,1]]

最佳答案

这就是你想要的:

master = []

def recur(count, current):
    count += 1
    if (count == 5):
        return

    new_current = current.copy()

    new_current.append(1)
    master.append(new_current)

    recur(count, new_current)


recur(0, [])

print(master)

问题是 current 是对列表对象的引用...而不是实际的列表本身。因此,当您将 current append 到 master 时,您只是 append 了对同一列表对象的引用。因此,当您将新元素添加到 current 列表时,它会添加到所有引用都指向的一个列表中。

解决方案是采用copy current 列表来存储当时的状态。 copy 有不同类型- 深和浅。浅拷贝将复制列表对象,但不会复制其元素,如果您有一个列表列表,则深复制将递归遍历元素和任何子元素。

关于python递归追加到列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59802542/

相关文章:

python - Flask POST 请求返回主网页而不是返回结果

python - 带有膨胀和 "VALID"填充的 tf.conv3d 尺寸不一致

java - 二叉树的直径 - 更好的设计

c++ - 如何使用内联和递归?

javascript - 使json符合Bootstrap Treeview格式

python - 在 Pandas 中读取带有波斯字符的 Excel 文件

Python:每秒运行循环并触发函数5秒

c++ - 搜索遍历多个列表的项目

python - 用另一个列表中相同索引处的值替换列表中的错误值

C++ - 将数字添加到列表中? (像 python )