我想把2D数组的一个新实例传递给一个函数。我试过常用的答案,比如使用列表(旧的)或做一个旧的[:]。但我还是得到了同样的证明。
我能想到的唯一原因是使用嵌套方法,由于我的C背景,我不太理解这些方法。如果有人能解释为什么代码以这种方式运行,这将真正帮助我理解python的魔力。你知道吗
复制代码(编辑以使其最小化和更具描述性)-
from pprint import pprint as pp
class Solution:
def solveNQueens(self, a):
b1 = [['.' for i in range(a)] for j in range(a)] #base list with queens positions and empty positions
b2 = list(b1) #to make a seperate list with na positions marked as x
def fillRows(i, j, b, p):
b[i][j] = 'Q' #add queens position
for x in range(i + 1, a):
p[x][j] = 'x' #cross straight entries
return b, p
def queenFill(i, b, p):
for j, e in enumerate(p[i]):
if e == '.':
pp(p)
bx = []
bx.extend(b) # trying to create new array duplicate that original array is unaffected by fillRows
# but as seen from print p is getting changed still, it should be same for every print call
px = []
px.extend(p)
bt, pt = fillRows(i, j, list(bx), list(px)) #trying to create new array duplicate using another method
queenFill(0, b1[:], b2[:]) #trying to create new array duplicate using another method
s = Solution()
s.solveNQueens(4)
我得到的结果是-
[['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.']]
[['Q', '.', '.', '.'],
['x', '.', '.', '.'],
['x', '.', '.', '.'],
['x', '.', '.', '.']]
[['Q', 'Q', '.', '.'],
['x', 'x', '.', '.'],
['x', 'x', '.', '.'],
['x', 'x', '.', '.']]
[['Q', 'Q', 'Q', '.'],
['x', 'x', 'x', '.'],
['x', 'x', 'x', '.'],
['x', 'x', 'x', '.']]
虽然它应该是这样的,因为我没有改变我在任何地方打印的变量,我正在创建副本的-
[['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.']],
[['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.']]
[['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.']]
[['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.'],
['.', '.', '.', '.']]
b1
是包含内部list
的list
。复制它,使用list(b1)
或b1[:]
复制外部list
,但不复制内部list
如果您也想复制内部列表,请尝试使用^{} 。你知道吗
相关问题 更多 >
编程相关推荐