Skip to main content
 首页 » 编程设计

python之无法在嵌套函数内的python中按值传递

2024年11月24日18xxx_UU

<分区>

我想将一个新的二维数组实例传递给一个函数。我已经尝试了常见的答案,比如使用列表(旧)或做一个旧的 [:]。我仍然得到相同的引用。
我能想到的唯一原因是使用嵌套方法,由于我的 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', '.']] 

虽然它应该是这样的,因为我没有更改我在任何地方打印的变量,但我正在创建它的副本 -

   [['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.']], 
[['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.']] 
[['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.']] 
[['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.'], 
     ['.', '.', '.', '.']]