Python - 带有列表的意外输出(我想不出如何在标题中说出这个)

时间:2014-02-20 00:39:58

标签: python plot

我正在为Python创建一个非常基本的ASCII绘图模块。当我调用graph.plot()函数时,它会忽略Y并在主列表中的所有列表中绘制X坐标的图标。

class Plotsy():
    def __init__(self):
        self.config("#", [3, 3])
    def config(self, icon, size):
        #Choose the plotted icon
        self.icon = icon
        #Make "size" useable throughout the object for math
        self.size = size
        #Create the grid
        self.graph = [["@"] * self.size[0]] * self.size[1]
    def plot(self, coords):
        self.graph[coords[1]][coords[0]] = self.icon
    def draw(self):
        pass
#A very short example to plot things
graph = Plotsy()
graph.plot([1, 2])
#After this problem is resolved, this will be replaced with my draw() function to print it correctly
print graph.graph

图形变量的工作原理如下 - 最外面的列表中的列表是Y(这些列表将在各自的行上打印),这些列表中的值用于X坐标。 plot()接受一个参数,它是X和Y坐标的列表。

为什么会这样做,我该如何解决?

2 个答案:

答案 0 :(得分:0)

["@"]*N按预期创建列表

然而[["@"]*N]*Y使Y指向同一列表... 这意味着每当您更改任何列表时,他们都会更改

答案 1 :(得分:0)

问题来自于您的graph成员在其config方法中初始化:

self.graph = [["@"] * self.size[0]] * self.size[1]

与您期望的行为相反,这会设置一个列表,其中包含3(self.size[1])次列表["@", "@", "@"]的相同实例。因此,如果您将一个点绘制到网格的任何行中,它将显示在所有行中,因为所有行实际上都是同一个列表对象的别名。因此,不是一遍又一遍地复制相同的列表引用[或3x],而是为网格中的每一行实例化一个新列表。为此,请使用迭代:

self.graph = [["@"] * self.size[0] for _ in range(self.size[1])]

这将按照需要进行。

>>> graph = Plotsy()
>>> graph.plot([1, 1])
>>> print '\n'.join([''.join([col for col in row]) for row in graph.graph])
@@@
@#@
@@@