Skip to main content
 首页 » 编程设计

python之在 Python 3 中创建随机空白矩阵(二维数组)

2024年10月25日11haluo1

我正在尝试在不使用 numpy 的情况下在 python 3 中创建一个随机空白矩阵。 代码看起来很完美,但是当我更改单个单元格的值(例如 Square 1 [0])时,它会更改所有 Square 1 [x] 个值。

#!/usr/bin/env python3 
 
# Creating a random n*n blank matrix 
#for example 6*6 
 
#I'll just create coloumns 
def one(): 
 
    square = [] 
    for x in range(6): 
        square.append(None) 
 
    Square = [] 
    for x in range(6): 
        Square.append(square) 
 
    return Square 
 
#output is exactly what i want 
print(one()) 
 
#but when i try to change a single value(cell), 
 
a = one() 
 
a[2][2] = "Error" 
 
#it's bullshit 
print(a) 

我或我的代码有什么问题吗?

请您参考如下方法:

Square 是一个包含六个引用的列表,它们都指向同一个 square 列表。修改任何这些 square 引用都会影响所有行。您可以通过查看行的 id 值来确认这一点:

a = one() 
print id(a[0]) 
print id(a[1]) 

结果:

37725768 
37725768 

与其创建一个 square 并将其追加六次,不如创建六个 square 并每个追加一次。

def one(): 
    Square = [] 
    for y in range(6): 
        square = [] 
        for x in range(6): 
            square.append(None) 
        Square.append(square) 
    return Square 

现在这些行都将引用不同的列表。

a = one() 
print id(a[0]) 
print id(a[1]) 
#result: 
#37827976 
#37829192 

我还建议更改 square 的名称,因为拥有两个仅大小写不同的变量名称会让人很困惑。

def make_matrix(): 
    matrix = [] 
    for y in range(6): 
        row = [] 
        for x in range(6): 
            row.append(None) 
        matrix.append(row) 
    return matrix