【问题标题】:List resets after for loopfor循环后列表重置
【发布时间】: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 循环末尾的 printreturn 语句都返回一个空列表。我该如何解决这个问题?

【问题讨论】:

  • 你能给我们提供一个有效的输入来测试吗?
  • 与您的问题无关,但作为一个小改进,您可以使用for y, layer in enumerate(map)for x, tile in enumerate(layer),然后您就不必执行x = 0x += 1
  • 另一个无关紧要的小改进,您可以在 Python 中使用0 &lt;= chance &lt;= 2,同样使用3 &lt;= chance &lt;= 4
  • 另一个不相关的改进,不要调用函数参数map或任何其他变量,这样你是在隐藏python的内置map函数。
  • @JiříBaum 我现在明白了。不知何故没有注意到它将地图中的 -1 更改为不同的数字,因此每次调用它时都会返回一个空列表

标签: python list loops for-loop


【解决方案1】:

总结来自 cmets 的变化:

def get_chest_tiles(the_map):
    chest_tiles = []
    for y, layer in enumerate(the_map):
        for x, tile in enumerate(layer):
            if tile in (-1, 18, 19, 20):
                chest_tiles.append((x * 16, y * 16))

            if tile == -1:
                chance = random.randint(0, 5)
                if 0 <= chance <= 2:
                    the_map[y][x] = 18
                elif 3 <= chance <= 4:
                    the_map[y][x] = 19
                else:
                    the_map[y][x] = 20

    print(chest_tiles)
    return chest_tiles

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多