Python-意外的列表输出(我想不出如何在标题中使用这个词)

Python-意外的列表输出(我想不出如何在标题中使用这个词),python,plot,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 #Mak

我正在为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
graph变量的工作原理是这样的-最外层列表中的列表是Y(这些列表将打印在它们自己的行上),这些列表中的值用于X坐标。 plot()接受一个参数,即X和Y坐标的列表

它为什么会这样做,我如何修复它?

[“@”]*N
按预期创建您的列表

但是,
[[“@”]*N]*Y
使Y指针指向同一列表。。。
这意味着,每当您更改列表中的任何一个时,它们都会更改

这些问题都是由类的
图形
成员在其
配置
方法中的初始化引起的:

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

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])
@@@
@#@
@@@

你期望什么样的输出?对不起,我赶时间。该图标出现在graph.graph(Y)的所有子列表中的X坐标上,但它不应该出现。基于代码,我希望输出如下:[['@'、'@'、'@']、['@'、'@'、'@'、'@']、['@'、'#'、'@']]基本上
[[['@]*N]*Y
没有做你认为是做的事,谢谢。我想不出一个可搜索的方法来找到这个问题——所以我预计会有人被骗。