【发布时间】:2014-05-14 18:58:06
【问题描述】:
我想要做的是遍历 board 中的元素,寻找“P”,然后检查是否有 5 个“P”连续(向下,可以这么说)。请参阅代码中的 cmets 以获得进一步的解释。尽管如此,inRow 仍然给我输出 15。
提示:五个“P”不应该是静止的,而是由玩家放置的,但在这个例子中,我只是放置了静止的。
board = [['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'P', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E'],
['E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E', 'E']]
# has 10 rows, with 10 elements in each
inRow=0
for y in range(10): # Loops over each row (y-index)
x=0 # x-index resets each new y-index loop (start on the first element (0) of each row)
for pos in board[y]: # pos loops over all elements in current row
if pos is "P": # checks if pos is "P"
for i in range(5): # loops over 0, 1, 2, 3, 4
if board[y+i][x] is "P": # when i=0, board[y+i][x] is ought to be where we find the first "P", then check if the following rows (we add +1 to y for each loop) is also "P"
inRow += 1 # Counter to see if we got 5 in a row
break
x+=1
print(inRow)
【问题讨论】:
-
作者希望
inRow是5,但得到了15。 -
不要将
is与字符串一起使用。is测试相同的对象,而不是相等的字符串。 -
您需要在嵌套循环中制作它吗?如果是这样,建议首先循环遍历列,然后遍历行。
-
@Daniel 好的!那么,改用 == 吗?
标签: python for-loop nested-loops