简体   繁体   English

python 二维数组,在分配循环内打印单个元素,与打印整个数组不同

[英]python 2d array, print single elements inside assign loop different from print the whole array

I have encounter a very strange python problem, code below.我遇到了一个很奇怪的python问题,代码如下。 I input a grid (2d array) [[7, 8, 9], [4, 5, 6], [1, 2, 3]]我输入一个网格(二维数组) [[7, 8, 9], [4, 5, 6], [1, 2, 3]]

from typing import List

def test(
        height: int,
        width: int,
        grid: List[List[int]]):

    print(grid)

    refList = [[0]*width]*height
    for h in range (0, height):
        for w in range (0, width):
            if h == 0 and w == 0:
                refList[h][w] = grid[h][w]
            elif(h < 1):
                refList[h][w] = refList[h][w-1] +grid[h][w]
            elif(w < 1):
                refList[h][w] = refList[h-1][w] + grid[h][w]
            else:
                refList[h][w] = grid[h][w] + max(refList[h-1][w], refList[h][w-1])
            print(refList[h][w])
    
    print(refList)

grid = [[7,8,9],[4,5,6],[1,2,3]]
test(3,3,grid)

I expect the output [[7,15,24],[11,20,30],[12,22,33]] .我期待 output [[7,15,24],[11,20,30],[12,22,33]] as you can see below, the print function inside the loop prints the correct answers, but after the loop finished and print the whole list, it gave me this [[12, 22, 33], [12, 22, 33], [12, 22, 33]] - basically all top row.正如您在下面看到的,循环内的 print function 会打印正确的答案,但是在循环完成并打印整个列表后,它给了我这个[[12, 22, 33], [12, 22, 33], [12, 22, 33]] - 基本上都是顶行。

[[7, 8, 9], [4, 5, 6], [1, 2, 3]]
7
15
24
11
20
30
12
22
33
[[12, 22, 33], [12, 22, 33], [12, 22, 33]]

What is going on here and how can I fix this?这是怎么回事,我该如何解决?

You are experimenting an issue due to shallow copies .由于副本浅,您正在试验一个问题。 You should use:你应该使用:

refList = [[0 for i in range(width)] for j in range(height)]

in replacement of your current initialisation line:代替您当前的初始化行:

refList = [[0]*width]*height

Indeed, this last line create an array of reference to the same line-based array internally ( [[0]*width] ).实际上,最后一行在内部创建了一个对同一基于行的数组的引用数组( [[0]*width] )。 You can check that easily use the following code:您可以使用以下代码轻松检查:

refList = [[0]*3]*3
print(refList[0] is refList[1])  # Print True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM