python-3.x - 尝试将列表附加到另一个列表时,所有元素都会发生变化,即使我使用“listB.append(listA[:]”进行附加来创建副本
问题描述
我正在尝试创建字段状态和移动列表。我通过附加当前字段状态来做到这一点,然后移动到一个列表中。但是,当我更改“字段”变量并再次附加它时,它会将列表中的所有元素更改为最新的。
我知道我正在附加一个参考,但是当我附加 'field[:]' 时它仍然不起作用,这应该创建一个副本。
抱歉,代码格式不正确,但在我的笔记本电脑上无法正常工作,已在我的原始代码中进行了格式化
data = []
for i in range(0,1):
field = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
play = True
while play:
compPlayed = False
comp2Played = False
# Loop until legal move made, which is when chosen field space = 0
while comp2Played == False:
compRow2 = random.randint(0, 2)
compCol2 = random.randint(0, 2)
if field[compRow2][compCol2] == 0:
# Create array containing the current field, and the legal move to be made
gameArray = ([field,[compRow2,compCol2]])
# Append copy to data list
data.append(gameArray[:])
print(data)
# Update field and end loop
field[compRow2][compCol2] = 1
comp2Played = True
我希望“数据”列表包含每个字段状态和移动,但每次附加时,字段值都会更改为最新的,但移动保持不变。
>>[[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [2, 0]]]
>>[[[[2, 0, 0], [0, 0, 0], [1, 0, 0]], [2, 0]], [[[2, 0, 0],
[0, 0, 0], [1, 0, 0]], [0, 2]]]
这是我输出的一个例子。从第一次打印和第二次打印开始,字段值会发生变化。
解决方案
推荐阅读
- javascript - 如何使用纯 javascript 检测全屏 api 支持?
- r - 我创建的用于返回 ggplot 对象的函数返回错误
- r - 通过R中的经度和纬度双重过滤数据 - 在给定坐标内搜索国家
- r - 如何使用 R 生成零度 B 样条
- c++ - boost json解析器的问题
- python - 从元组列表中的项目构建 2D numpy 数组
- mongodb - 将 flask-wtf 形式的文件保存到 MongoDB 的 GridFS
- visual-studio-2017 - Visual C++ 项目系统包
- c# - Xamarin 表单单元测试命令
- javascript - 如何断开匿名 MutationObserver 与文档元素的连接,而不用其克隆替换元素?