【发布时间】:2022-01-16 01:26:53
【问题描述】:
一个列表在函数的开头定义,然后附加到一个for循环中,并在返回一个空列表的函数末尾打印。
代码:
def get_chest_tiles(map):
chest_tiles = []
y = 0
for layer in map:
x = 0
for tile in layer:
if tile == -1:
chest_tiles.append((x * 16, y * 16))
#print(chest_tiles) #* returns correct list
chance = random.randint(0, 5)
if chance >= 0 and chance <= 2:
map[y][x] = 18
elif chance >= 3 and chance <= 4:
map[y][x] = 19
else:
map[y][x] = 20
x += 1
y += 1
print(chest_tiles) # returns []
return chest_tiles # returns []
追加下被注释掉的打印语句返回如下:
[(864, 48)]
[(864, 48), (960, 48)]
[(864, 48), (960, 48), (0, 160)]
[(864, 48), (960, 48), (0, 160), (208, 160)]
这是预期的。
for 循环末尾的 print 和 return 语句都返回一个空列表。我该如何解决这个问题?
【问题讨论】:
-
你能给我们提供一个有效的输入来测试吗?
-
与您的问题无关,但作为一个小改进,您可以使用
for y, layer in enumerate(map)和for x, tile in enumerate(layer),然后您就不必执行x = 0和x += 1等 -
另一个无关紧要的小改进,您可以在 Python 中使用
0 <= chance <= 2,同样使用3 <= chance <= 4 -
另一个不相关的改进,不要调用函数参数
map或任何其他变量,这样你是在隐藏python的内置map函数。 -
@JiříBaum 我现在明白了。不知何故没有注意到它将地图中的 -1 更改为不同的数字,因此每次调用它时都会返回一个空列表
标签: python list loops for-loop