python - 循环列表列表(嵌套 for 循环)并不像我想要的那样工作

标签 python for-loop nested-loops

我想要做的是循环board中的元素,查找“P”,然后检查是否有连续的5个“P”(可以这么说,向下) )。请参阅代码中的注释以获取进一步的解释。不过,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 “P”连续。想一想:

第一次在第二行点击“P”时,倒计时,您会得到 5 。下次当您在外侧敲击“P”时for循环,倒计时,你会得到 4 。现在您已经数过 9 “P”。继续这个,你会得到5 + 4 + 3 + 2 + 1 = 15 “P”。

解决方案是使用中间计数器,并且仅将该中间计数添加到 inRow如果该计数器是 5 .

要正确计数,您可以在 for pos in board[y]: 之后声明一个计数器

counter = 0

然后,代替 inRow += 1 ,您使用counter += 1 .

最后,在break语句之前,进行检查:

if counter == 5:
    inRow += counter

关于python - 循环列表列表(嵌套 for 循环)并不像我想要的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23662922/

相关文章:

python - 使用 python 编码从 Excel 读取字符串的缺点 ('utf-8' )

python - 使用 OpenCV + Python + Mac 编写视频

python - `for` 循环如何在字典上具体工作

c - 如何检查整数是否是数组中元素的线性组合?

java - 返回 boolean 值的嵌套 for 循环上的死代码

c++ - 使用 std::ranges 摆脱嵌套的 for 循环

python - 从 QLineEdit 读取文本作为 Qmenu 选项的子菜单

Python:Qt-Gui 和几个任务

loops - 如何在 python 中执行 C++ 样式(索引)嵌套循环?

python - 清理笨重的 for 循环