我是 Python 的新手(以及整个编程)。我很确定这个问题的答案很明显,但我真的不知道该怎么做。
def do_play(value, slot, board):
temp=board
(i,j) = slot
temp[i][j] = value
return temp
board 是列表的列表。值是一个整数。插槽是和整数元组。
我在这里要做的是
- 喂功能板
- 将 board 复制到名为 temp 的新列表
- 在 temp 中的特定位置插入一个新值
- 返回温度,保持电路板不变
当我运行这个 shell 时,原始列表 (board) 和新列表 (temp) 都会改变。 =\
如有任何帮助,我们将不胜感激。
最佳答案
temp=board
不会制作新的板子。它使 temp
变量引用与 board
完全相同的列表。所以改变 temp[i][j]
也会改变 board[i][j]
。
要制作副本,请使用
import copy
temp=copy.deepcopy(board)
请注意 temp=board[:]
使 temp
引用一个新列表(不同于 board
,但内容(即,列表中的列表)仍然是相同的:
In [158]: board=[[1,2],[3,4]]
In [159]: temp=board[:]
修改 temp
也会修改 board
:
In [161]: temp[1][0]=100
In [162]: temp
Out[162]: [[1, 2], [100, 4]]
In [163]: board
Out[163]: [[1, 2], [100, 4]]
id
显示对象的内存地址。这表明 temp
和 board
是不同的列表:
In [172]: id(temp)
Out[172]: 176446508
In [173]: id(board)
Out[173]: 178068780 # The ids don't match
但这表明 temp
中的第二个列表与 board
中的列表完全相同:
In [174]: id(temp[1])
Out[174]: 178827948
In [175]: id(board[1])
Out[175]: 178827948 # The ids are the same
但是如果你使用copy.deepcopy
,那么列表中的列表也会被复制,如果修改temp
是离开board,这就是你需要的
不变:
In [164]: import copy
In [165]: board=[[1,2],[3,4]]
In [166]: temp=copy.deepcopy(board)
In [167]: temp[1][0]=100
In [168]: temp
Out[168]: [[1, 2], [100, 4]]
In [169]: board
Out[169]: [[1, 2], [3, 4]]
关于Python - 函数有一个列表作为参数。如何在不更改第一个列表的情况下返回另一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3964967/