【问题标题】:Using index of a value to loop through a list of lists in Python使用值的索引循环遍历 Python 中的列表列表
【发布时间】:2021-06-13 09:02:17
【问题描述】:

我在列表列表中有一个 Connect4 板,如下所示:

    currentgame =[["_", "_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_", "_"], ["_", "_", "_", "_", "_", "_"]]

我正在尝试进行横向胜利检查,我将检查索引的值是否为 X 或 O,记录该值的索引,跳转到下一列并检查相应的空格。

    rowwinO = 0
    rowwinX = 0
    for column in range(0, 7, 1):
        for row in range(0, 6, 1):              
            if currentgame[column][row] == "X":
                row += 1
                column += 1
                rowwinX += 1
                rowwinO = 0
                if rowwinX == 4:
                    winner = True
                    print("Player 1 Wins! Congratulations")
            elif currentgame[columnrun][row] == "O":
                row +=1
                column += 1
                rowwinO +=1
                rowwinX = 0
                if rowwinO == 4:
                    winner = True
                    print("Player 2 Wins! Congratulations!")
            else:
                row += 1
                rowwinX = 0
                rowwinO = 0

代码显然不起作用...不胜感激 - 我仍然不确定是否真的有可能以这种方式中断和弄乱 for 循环。谢谢!

【问题讨论】:

  • 为什么在里面增加rowcolumn,没有影响
  • 在确定获胜者后打破循环,您可以使用break

标签: python list loops indexing


【解决方案1】:

这是一个稍微不同的方法,它从 row 和 cols 创建字符串,然后检查 XXXOOO 是否在这些字符串中。

# horizontal
for l in cgame:
    if 'XXX' in ''.join(l):
        print("Player 1 Wins! Congratulations")
        break
    elif 'OOO' in ''.join(l):
        print("Player 2 Wins! Congratulations")
        break

# vertical
for i in range(len(cgame[0])):
    cCol = [j[i] for j in cgame]
    if 'XXX' in ''.join(cCol):
        print("Player 1 Wins! Congratulations")
        break
    elif 'OOO' in ''.join(cCol):
        print("Player 2 Wins! Congratulations")
        break

【讨论】:

  • 谢谢,这看起来很有用。虽然我想一旦值不是字符串就很难使用
  • @JuozapasBagdonas 的值是多少?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-26
  • 2019-04-15
  • 2019-01-15
  • 1970-01-01
相关资源
最近更新 更多