奇怪的循环并在其中附加功能

时间:2014-04-28 12:57:07

标签: python

我目前正在尝试理解python程序的代码,它本质上是一个pacman游戏。当我在阅读代码时,我发现了一个奇怪的循环,似乎将列表重置为“空”,然后将值附加到此列表。这就是我的意思:

def drawFood(self, foodMatrix ):
    foodImages = []    


    color = FOOD_COLOR 
    for xNum, x in enumerate(foodMatrix):                                                                   
        if self.capture and (xNum * 2) <= foodMatrix.width: color = TEAM_COLORS[0]   
        if self.capture and (xNum * 2) > foodMatrix.width: color = TEAM_COLORS[1]


        imageRow = []                                               
        foodImages.append(imageRow)                                                                          
        for yNum, cell in enumerate(x):                             
            if cell: # There's food here

                screen = self.to_screen((xNum, yNum ))                                                  

                dot = circle( screen,                                                                                 
                              FOOD_SIZE * self.gridSize,
                              outlineColor = color, fillColor = color,
                              width = 1)                                                                                
                imageRow.append(dot)                                                                                             
            else:
                imageRow.append(None)
    print('foodimages' + str(foodImages))            
    return foodImages 

尽管foodImages = []imageRow = []在循环的每次迭代中都被重置为空,但foodImages列表似乎仍在继续增长。

是否有可能因为imageRowimageRowfoodImages添加点foodImages列表继续增长,尽管imageRow是{{1}}设置为空?

2 个答案:

答案 0 :(得分:1)

代码可能有点令人困惑。

imageRow = []                                               
foodImages.append(imageRow) 
...
imageRow.append("something")

foodImages仅在开始时设置为空列表。 即使您在此处向imageRow添加空foodImages,您仍然可以在以后处理同一个imageRow对象。因此,当您在代码中进一步向imageRow添加内容时,它将反映在foodImages列表中(其中包含imageRow对象)。

答案 1 :(得分:-1)

Python似乎将list视为intstr。请参阅下面的示例。 list就像C编程语言中的引用或指针一样。

#example 1
>>> a = []
>>> x = 1
>>> a.append(x)
>>> a
[1]
>>> x = 2
>>> a
[1]

#example 2
>>> a = []
>>> x = "hoge"
>>> a.append(x)
>>> a
['hoge']
>>> x = "fuga"
>>> a
['hoge']

#example 3(your problem)
>>> a = []
>>> x = [1]
>>> a.append(x)
>>> a
[[1]]
>>> x[0] = 2
>>> a
[[2]]