【问题标题】:How to check if all items within a list of lists are the same如何检查列表列表中的所有项目是否相同
【发布时间】:2021-09-17 17:32:42
【问题描述】:

我正在使用 Python 开发井字游戏(以提高我的 Python 技能),但遇到以下问题:我有一个类似下面的列表,根据是否全部确定玩家是否获胜垂直、水平或对角线的值都具有相同的值。

win_horizontal = [[board[0], board[1], board[2]], [board[3], board[4], board[5]], [board[6], board[7], board[8]]]

win_vertical = [[board[0], board[3], board[6]], [board[1], board[4], board[7]], [board[2], board[5], board[8]]]

win_diagonal = [[board[0], board[4], board[8]], [board[2], board[4], board[6]]]

所以目前我的逻辑如下:

result = False;
result = all(elem == mark for elem in win_horizontal[1])
if result :
    print("All Elements in List are Equal")
else:        
    print("All Elements in List are Not Equal")

这有效,因为我只检查列表中的一个列表。但是,我不确定如何检查所有列表,以确定玩家是否在对角线、水平线或垂直线上获胜。我希望能够检查所有列表列表。

我尝试了以下

def win_check(board, mark):
    win_horizontal = [[board[0], board[1], board[2]], [board[3], board[4], board[5]], [board[6], board[7], board[8]]]
    win_vertical = [[board[0], board[3], board[6]], [board[1], board[4], board[7]], [board[2], board[5], board[8]]]
    win_diagonal = [[board[0], board[4], board[8]], [board[2], board[4], board[6]]]
    
    winner = [win_horizontal, win_vertical, win_diagonal]
        
    result = False;
    result = all(elem == mark for elem in any(winner))
    if result :
        print("All Elements in List are Equal")
    else:        
        print("All Elements in List are Not Equal")

但我只是收到以下错误 TypeError: 'bool' object is not iterable,我认为它是从 any(winner)) 引发的

检查获胜条件的最佳方法是什么?

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    您需要在水平、垂直、对角线之间有一个any,每个上都有一个all

    result = any(
        all(elem == mark for elem in win)
        for win in winner
    )
    

    【讨论】:

      【解决方案2】:

      检查玩家的获胜模式可能比检查 3 个棋盘位置是否相等更简单。

      player        = 'X'             # last played
      winPattern    = [player]*3
      boardPatterns = win_horizontal + win_vertical + win_diagonal
      if winPattern in boardPatterns:
          print(player,'wins!')
      

      附带说明,您不必将 3 个轴方向分隔为 3 个变量,您可以构建一个模式列表以供使用:

      positions = [(0,1,2),(3,4,5),(6,7,8),(0,3,6),(1,4,7),(2,5,8),(0,4,8),(2,4,6)]
      boardPatterns = [[board[p] for p in axis] for axis in positions]
      

      【讨论】:

        【解决方案3】:
        from typing import Optional, Any
        
        TEAM_A = True
        TEAM_B = False
        
        class Board:
          # Calculated victory patterns
          VICTORY_CELLS = [
            [0,1,2], [3,4,5], [6,7,8],  # horizontal
            [0,3,6], [1,4,7], [2,5,8],  # vertical
            [0,4,8], [2,4,6],  # diagonal
          ]
          def __init__(self):
            self._vector: list[Optional[Any]] = [None for _ in range(9)]
        
          def check_winner(self, marker) -> bool:
            # Get set of indexes where player has put his marker
            player_cells = {i for i, v in enumerate(self._vector) if v == marker}
            # For every victory pattern, if it is a subset of players markers, return True
            return any(player_cells.issuperset(victory) for victory in self.VICTORY_CELLS)
        
          def __setitem__(self, key, value):
            if isinstance(key, int) and 0 <= key <= 8:
              self._vector[key] = value
        
        board = Board()
        board[0] = TEAM_A
        board[4] = TEAM_A
        print('Team A victory: ', board.check_winner(TEAM_A))
        print('Team B victory: ', board.check_winner(TEAM_B))
        board[8] = TEAM_A
        print('Team A victory: ', board.check_winner(TEAM_A))
        print('Team B victory: ', board.check_winner(TEAM_B))
        

        结果将是:

        Team A victory:  False
        Team B victory:  False
        Team A victory:  True
        Team B victory:  False
        

        你应该确保胜利后游戏不会继续。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-20
          • 1970-01-01
          • 2023-03-03
          • 1970-01-01
          相关资源
          最近更新 更多