python - 如何将变量的值保存在列表中,而不是变量本身?
问题描述
我的问题是,当我将变量附加到 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
只是用同一个列表填充了几次
解决方案
制作列表的副本:
all_graphs.append(list(first_graph))
推荐阅读
- android - buildozer Python kivy中的Android应用程序部署错误
- python - 带有 Django 的 Gunicorn 给出了静态文件的问题
- git - .git 里面的 git repo 和分支没有显示
- swift - Vapor 3 你如何表示时间跨度
- flutter - 将 DropdownButtons 和 TextField 选定的数据保存到列表中
- javascript - Javascript阻止问号输入
- javascript - 选择单选按钮时如何为标签添加边框
- reactjs - 使用 react/typescript 中的最终形式从嵌套形式中获取值
- node.js - 问题 docker 与 pm2 和 nginx
- c# - 如何让我的 c# 控制台应用程序与 app.config 一起运行?