首页 > 解决方案 > 如何将变量的值保存在列表中,而不是变量本身?

问题描述

我的问题是,当我将变量附加到 python 中的列表时,它会将指针保存到列表中的值而不是值本身。这意味着当我更改附加到列表的变量时,列表中的值也会更改,这是我不想要的。我想在将变量附加到列表的那一刻保存变量的当前值,并且在附加后不会再改变。

这是代码,我希望我能说清楚:

while j < n:
    if first_graph[j] == (n-1):
        while first_graph[j] == (n-1) and j < n-1:
            j += 1
        if first_graph[j] == (n-1) and j == n-1:
            j += 1
        else:
            first_graph[j] += 1
            for i in range(j):
                first_graph[i] = 0
            all_graphs.append(first_graph)
            j = 0
    else:
        first_graph[j] += 1
        all_graphs.append(first_graph)

这显然不是全部,但我的问题是列表first_graph中的all_graphs更改时会更新,所以最后all_graphs只是用同一个列表填充了几次

标签: pythonlistvariables

解决方案


制作列表的副本:

all_graphs.append(list(first_graph))

推荐阅读