无法替换 Python 中的二维数组中的值

Can't subsitute a value in a 2d array in Python

所以,我正在尝试制作一个 python 程序,它需要替换 python 二维数组中的一个值,但不知何故它无法正常工作,给我的结果如下:

[0, M, 0, M]
[0, M, 0, M]
[0, M, 0, M]
[0, M, 0, M]

当它应该给我这样的结果时:

[0, 0, 0, M]
[0, M, 0, 0]
[0, 0, 0, 0]
[0, 0, 0, 0]

拜托,如果有人能告诉我错误的原因,我将不胜感激。

import random
import sys
import os

def genwmap(minv, maxv, mode):
    wmap = []
    temp = []
    mx = random.randint(minv, maxv)
    my = random.randint(minv, maxv)
    for element in range(0, mx):
        temp.append("0")
    for element in range(0, my):
        wmap.append(temp)
    temp = random.randint(int(minv*maxv/15), int(minv*maxv/5)) #Use temp var to generate region's count
    if mode == 1:
        for element in range(0, temp):
            one = random.randint(0, len(wmap)-1)
            two = random.randint(0, len(wmap[0])-1)
            wmap[one][two] = "M"
            for element in wmap:
                print(element)
            print(wmap[1][1])
            print("one: " + str(one))
            print("two: " + str(two))
    return wmap

r = genwmap(10, 20, 1)
for element in r:
    print(element)

此代码按预期工作。

def genwmap(minv, maxv, mode):

    mx = random.randint(minv, maxv)
    my = random.randint(minv, maxv)

    wmap = [["0" for _ in range(mx)] for _ in range(my)]

    temp = random.randint(int(minv*maxv/15), int(minv*maxv/5))  # Use temp var to generate region's count

    if mode == 1:

        for element in range(temp):
            one = random.randint(0, len(wmap)-1)
            two = random.randint(0, len(wmap[0])-1)
            wmap[one][two] = "M"
            for element in wmap:
                print(element)
            print(wmap[1][1])
            print("one: " + str(one))
            print("two: " + str(two))
    return wmap


r = genwmap(10, 20, 1)
for element in r:
    print(element)

你的问题是你创建二维数组的那些行:

for element in range(0, mx):
        temp.append("0")

for element in range(0, my):
        wmap.append(temp)

这里你创建一个数组,看起来像这样

[
 temp,
 temp,
 temp,
]

看到他们都是一样的。这也是 python 如何处理内存以及如何节省内存。然后,当您将 temp 添加到 wmap 列表时,不只是制作一个新副本,而是始终链接到同一列表 temp 以节省内存