Python - 函数有一个列表作为参数。如何在不更改第一个列表的情况下返回另一个列表?
我对 Python(以及整个编程)还很陌生。我很确定这个问题的答案是显而易见的,但我真的不知道该怎么办。
def do_play(value, slot, board):
temp=board
(i,j) = slot
temp[i][j] = value
return temp
board 是一个列表的列表。值是一个整数。槽是和整数元组。
我在这里想做的是将
- 功能板
- 复制板提供给一个名为 temp 的新列表,
- 在 temp 的特定位置插入一个新值
- 返回 temp,保持板不变
当我运行这是 shell 时,原始列表都是原始列表(board) 和新列表 (temp) 发生变化。 = \
任何帮助将不胜感激。
I'm pretty new in Python (and programming as a whole). I'm pretty sure the answer to this is obvious, but I really don't know what to do.
def do_play(value, slot, board):
temp=board
(i,j) = slot
temp[i][j] = value
return temp
board is a list of lists. value is an integer. slot is and integer tuple.
What I am trying to do here is to
- feed the function board
- copy board to a new list called temp
- insert a new value in a specific location in temp
- return temp, leaving board unchanged
When I run this is the shell, both the the original list (board) and the new list (temp) change.
= \
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
temp=board
不会制作新板。它使temp
变量引用与board
完全相同的列表。因此,更改temp[i][j]
也会更改board[i][j]
。要制作副本,请使用
注意
temp=board[:]
使temp
引用新列表(与board
不同,但内容(即列表中的列表)仍然相同:修改
temp
也会修改board
:id
显示对象的内存地址。显示temp
和board
是不同的列表:但这显示
temp
内的第二个列表与board
内的列表完全相同>:但是如果你使用
copy.deepcopy
,那么列表中的列表也会被复制,如果修改temp
是为了离开board<,这就是你所需要的/代码> 不变:
temp=board
does not make a new board. It makes thetemp
variable reference the very same list asboard
. So changingtemp[i][j]
changesboard[i][j]
too.To make a copy, use
Note that
temp=board[:]
makestemp
refer to a new list (different thanboard
, but the contents (that is, the lists within the list) are still the same:Modifying
temp
modifiesboard
too:id
shows the object's memory address. This showstemp
andboard
are different lists:But this shows the second list inside
temp
is the very same list insideboard
:But if you use
copy.deepcopy
, then the lists within the list also get copied, which is what you need if modifyingtemp
is to leaveboard
unchanged:您是否正在尝试复制
board
?或者也许这是为了复制结构。
Are you trying to copy
board
?Or maybe this to copy the structure.
使用
copy.deepcopy()
进行复制物体。Use
copy.deepcopy()
to copy the object.这里
temp
是对board
的引用,一个浅拷贝。我通常喜欢导入复制模块(import copy
)并使用copy.deepcopy
,这使得temp
与板分离。你可以这样称呼它:否则,你可以只制作一块板(这也可以制作一个深层副本)。我相信这应该可行,但我还没有在列表列表上尝试过。你可以这样称呼它:
Here
temp
is a reference toboard
, a shallow copy. I usually like to import the copy module (import copy
) and usecopy.deepcopy
which makestemp
separate from board. You'd call it something like this:Otherwise, you can just make a slice of board (which also makes a deep copy). I believe this should work, but I haven't tried it on a list of lists. You'd call it as so:
这不会复制列表,它只是对同一对象再添加一个引用。请改用
temp = board[:]
。This doesn't copy list, it just makes one more reference to the same object. Use
temp = board[:]
instead.