在Python中使用for循环将子矩阵设置为一个值[重复]

问题描述 投票:0回答:1

我一直在为一个简单的Python问题而烦恼,但到目前为止还没有看到我的错误。我有这段代码,应该将 10 x 10 矩阵初始化为全零,然后将子矩阵设置为 1,但它的行为并不符合我的预期。

这是我尽可能简化的代码:

# Initialize matrix to all zeros
xs = 10
ys = 10
lights = [[0]*xs]*ys

# Set a 3 x 3 portion of the matrix to all ones
for y in range(3, 6):
    for x in range(5, 8):
        lights[y][x] = 1

# Print confusing results
count = 0
for y in range(ys):
    for x in range(xs):
        print(lights[y][x], end=' ')
        count += lights[y][x]
    print()
print(count)

我期待这个结果:

0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 
0 0 0 0 0 0 0 0 0 0 

我得到的是这样的:

0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 
0 0 0 0 0 1 1 1 0 0 

为什么所有行设置都相同?预先感谢您的任何见解。

python arrays for-loop matrix nested
1个回答
0
投票

代码中的问题在于初始化矩阵的行。

lights = [[0]*xs]*ys
行创建了一个矩阵,其中的行本质上是对同一列表的引用。因此,修改一行会影响所有其他行,从而导致意外行为。为了解决这个问题,建议使用列表理解,比如
lights = [[0] * xs for _ in range(ys)]
,它可以确保每一行都是一个独立的列表。这样,对一行所做的更改不会影响矩阵中的其他行。

© www.soinside.com 2019 - 2024. All rights reserved.