我如何在python中将for循环的增量设置为1? [重复]

问题描述 投票:3回答:3

此问题已经在这里有了答案:

我正在创建一艘战舰游戏,并希望检查玩家目标位置周围的位置,以检查那里是否有任何船只,即

!(https://imgur.com/a/9Dddom0

在该板上,程序将检查任何船舶的位置(2,0),(1,1),(2,2)和(3,1),如果存在,则子例程将返回True,并且如果不,它将返回False。

这是我当前的代码:

def RadarScan(Board, Ships, R, C):
    around = [[C, R - 1], [C + 1, R], [C, R + 1], [C - 1, R]]
    for i in around:
        for x in range(2):
            if int(i[x]) > 9 or int(i[x]) < 0:
                around.remove(i)
    near = False
    for i in range(len(around)):
        if Board[around[i][0]][around[i][1]] == "-" or "m" or "h":
            continue
        else:
            near = True
            break
    if near == True:
        return True
    else:
        return False

[检查目标板周围的位置是否在板上时,我使用for循环遍历周围的列表,该列表包含所有周围的位置,但是假设周围的第二个位置是(10,9), for循环会删除此位置,因为它不在板上,然后再递增到下一个位置,即第三个位置,但是只剩下原始位置1、3和4,因此它将跳过检查原始位置3,而是直接转到原始位置4。

(抱歉,这有点令人困惑)

所以我的问题是,我可以在“ around.remove(i)”下面添加一些内容,以使for循环“ for i in around”的增量后移1吗?

python list for-loop multidimensional-array increment
3个回答
1
投票

修改您要遍历的项目不起作用。

我不知道你为什么有int(i[x])。您希望RC不是整数吗?

Board[][] == "-" or "m" or "h"始终为True,因为"m" or "h"始终为True

您的循环最好写成:

for x, y in around:
    if x in range(10) and y in range(10):
        if Board[x][y] not in "-mh":
            return True
return False

0
投票

一种方法可能是手动索引,如果我正确理解了您的问题:

def RadarScan(Board, Ships, R, C):
    around = [[C, R - 1], [C + 1, R], [C, R + 1], [C - 1, R]]
    index = 0
    for i in range(len(around)):
        index += 1
        for x in range(2):
            if int(around[index][x]) > 9 or int(around[index][x]) < 0:
                around.remove(around[index])
                index -= 1

    near = False
    for i in range(len(around)):
        if Board[around[i][0]][around[i][1]] == "-" or "m" or "h":
            continue
        else:
            near = True
            break
    if near == True:
        return True
    else:
        return False

0
投票

For循环无法执行此操作。使用while循环:

def RadarScan(Board, Ships, R, C):
    around = [[C, R - 1], [C + 1, R], [C, R + 1], [C - 1, R]]
    c= 0
    while c < len(around)-1:
        i = around[c]
        for x in range(2):
            if int(i[x]) > 9 or int(i[x]) < 0:
                around.remove(i)
                c-= 1
        c += 1
    near = False
    for i in range(len(around)):
        if Board[around[i][0]][around[i][1]] == "-" or "m" or "h":
            continue
        else:
            near = True
            break
    if near == True:
        return True
    else:
        return False

这应该可以解决问题

© www.soinside.com 2019 - 2024. All rights reserved.