我目前正在尝试理解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列表似乎仍在继续增长。
是否有可能因为imageRow
和imageRow
向foodImages
添加点foodImages
列表继续增长,尽管imageRow
是{{1}}设置为空?
答案 0 :(得分:1)
代码可能有点令人困惑。
imageRow = []
foodImages.append(imageRow)
...
imageRow.append("something")
foodImages
仅在开始时设置为空列表。
即使您在此处向imageRow
添加空foodImages
,您仍然可以在以后处理同一个imageRow
对象。因此,当您在代码中进一步向imageRow
添加内容时,它将反映在foodImages
列表中(其中包含imageRow
对象)。
答案 1 :(得分:-1)
Python似乎将list
视为int
或str
。请参阅下面的示例。 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]]