This question already has answers here:
How to remove items from a list while iterating?
(27个答案)
24天前关闭。
我正在创建一个战列舰游戏,并想检查周围的位置,球员的目标位置,以检查是否有任何船只位于那里,即。
!(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循环通过包含所有周围位置的around列表递增,但是假设around的第二个位置是(10,9),for循环将删除这个位置,因为它不在板上,然后增加到周围的下一个位置,即第三个位置,但是周围只剩下原始位置1、3和4,因此它将跳过检查原始位置3,而直接转到原始位置4。
(如果有点混乱,很抱歉)
所以我的问题是,是否可以在“around.remove(I)”下面添加一些内容,将for循环“for I in around”的增量向后移动1?

最佳答案

修改正在迭代的项不起作用。
我不知道你为什么有。您希望int(i[x])R不是整数吗?
C总是Board[][] == "-" or "m" or "h"因为True总是"m" or "h"
你的循环最好写成:

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

关于python - 如何在python中将for循环的增量设置为1? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58568714/

10-11 22:16
查看更多