首页 > 解决方案 > 将一个多维列表的值设置为另一个多维列表的值

问题描述

我在 Python 3.9 中有一个包含多个字符串的多维列表。现在我想[["a", "b"], ["c", "d"]]成为[["d", "a"], ["b", "c"]]。所以每个字符串都向上移动一个位置。这是我尝试过的代码:

list = [["a", "b"], ["c", "d"]]
helper = list
list[0][0] = helper[1][1]
list[0][1] = helper[0][0]
list[1][0] = helper[0][1]
list[1][1] = helper[1][0]
print(list)

但不幸的是,代码给了我[['d', 'd'], ['d', 'd']]而不是[["d", "a"], ["b", "c"]]. helper在我的程序结束时打印出来[['d', 'd'], ['d', 'd']]也给了我,但为什么呢?助手不应该是[["a", "b"], ["c", "d"]]因为我将他设置list为我的程序的顶部。

list = [["a", "b"], ["c", "d"]]
helper = list

但是,以下代码证明在我的程序期间助手正在更改:
list = [["a", "b"], ["c", "d"]]
helper = list
print("Top of program:", helper)
list[0][0] = helper[1][1]
list[0][1] = helper[0][0]
list[1][0] = helper[0][1]
list[1][1] = helper[1][0]
print("Bottom of program:", helper)

输出:

Top of program: [['a', 'b'], ['c', 'd']]
Bottom of program: [['d', 'd'], ['d', 'd']]

所以我的问题是为什么helper改变它的值以及为什么我的程序没有做它应该做的事情。

标签: pythonmultidimensional-array

解决方案


推荐阅读