[英]Input parameter change as loop calls for another def (python 3.0), why?
我只是無法弄清楚為什么我的輸入參數(板)在循環中發生變化。
def迭代從definit進入列表“ board”。 它應該這樣做一次,我檢查了一下,它只調用了一次def initial。 問題在循環中“針對range(0,size())中的i:”發生。 在這里,列表“ old_board”有所更改。 如果我在“ old_board”列表中有5個回合和5個列表,則第二個回合會更改old_board [1]的值,依此類推。為什么會這樣? 我該如何解決呢?
(參數列表和循環中的列表應該相等)
這是輸出:
“這是參數列表:[[1,1,0,1,0],[1,1,1,0,1],[0,0,1,1,1],[1,1,0 ,1、1],[1、0、0、1、0]]
這是循環中的列表:[[1,1,0,1,0],[1,1,1,0,1],[0,0,1,1,1],[1,1, 0,1,1],[1,0,0,1,0]]
這是循環中的列表:[[0,0,0,1,0],[1,1,1,0,1],[0,0,1,1,1],[1,1, 0,1,1],[1,0,0,1,0]]
這是循環中的列表:[[0,0,0,1,0],[1,1,0,0,0],[0,0,1,1,1],[1,1, 0,1,1],[1,0,0,1,0]]
這是循環中的列表:[[0,0,0,1,0],[1,1,0,0,0],[0,0,0,1,0],[1,1, 0,1,1],[1,0,0,1,0]]
這是循環中的列表:[[0,0,0,1,0],[1,1,0,0,0],[0,0,0,1,0],[1,1, 0,1,0],[1,0,0,1,0]]“
這是代碼:
def iterate(board):
old_board = board
print('This is the parameter list :',old_board)
new_board = board
living = 0 # Value of alive cells in the future new board
for i in range(0,size()): # Nestled loop that iterate through the old board
print('This is the list in the loop:',old_board)
for j in range(0,size()): # and sets new values depending on the status of each old cell
new_value = living_neighbors(i,j,old_board)[1]
new_board[i][j] = new_value
living += new_value
print(new_board)
print(living)
return (living, new_board)
iterate(initiate()[0])
在這里,您無需復制列表,只需新建指向現有列表的鏈接
old_board = board
print('This is the parameter list :',old_board)
new_board = board
如果您需要它的副本,則應該這樣進行:
old_board = board[:]
print('This is the parameter list :',old_board)
new_board = board[:]
見常見問題
通過做這個
old_board = board
new_board = board
您無需創建新對象,而只需創建對現有對象的新引用即可。 您可以使用復制模塊或Alex建議的語法來創建新對象。
from copy import deepcopy
old_board = deepcopy(board)
在這里您可以找到詳細的說明: http : //www.python-course.eu/deep_copy.php
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.