在列表列表中查找相同索引上的匹配元素?

时间:2021-03-09 06:26:29

标签: python

我正在编写一个井字游戏,游戏板如下所示:

game = [[1, 0, 1],
        [1, 1, 0],
        [1, 1, 0],]

我正在尝试以下功能:

def vertical_win(game):
    for column, row in enumerate(game):
        check = []
        check.append(row[0])
        if check.count(check[0]) == len(check) and check[0] != 0:
            print("Winner")

输出:

Winner
Winner
Winner

它只迭代每个列表的第 0 个元素。如果数字显示每行每个数字的获胜者,而不是匹配每个列表的所有三个数字。

3 个答案:

答案 0 :(得分:1)

获取游戏板“列”的一种简单方法是使用zip()

>>> cols = [*zip(*game)]
>>> cols
[(1, 1, 1), (0, 1, 1), (1, 0, 0)]

从这里您可以通过会员测试检查是否获胜:

if (0, 0, 0) in cols:
    print("player 0 wins")
elif (1, 1, 1) in cols:
    print("player 1 wins")

组合起来:

def vertical_win(game):
    cols = [*zip(*game)]
    if (0, 0, 0) in cols:
        print("player 0 wins")
    elif (1, 1, 1) in cols:
        print("player 1 wins")

通过这个小的修改,您可以很容易地将其扩展到更大的电路板尺寸:

def vertical_win(game):
    n = len(game)
    cols = [*zip(*game)]
    if (0,)*n in cols:
        print("player 0 wins")
    elif (1,)*n in cols:
        print("player 1 wins")

至于为什么您的代码不起作用:

>>> def vertical_win(game):
...     for col, row in enumerate(game):
...             print(col, row)
...             check = []
...             check.append(row[0])
...             print(check)
...
>>>
>>> vertical_win(game)
0 [1, 0, 1]
[1]
1 [1, 1, 0]
[1]
2 [1, 1, 0]
[1]

对于所有三个迭代,此特定棋盘状态的布尔表达式 if check.count(check[0]) == len(check) and check[0] != 0 始终为真,因为 check[0] == 1check.count(1) == len([1])check[0] == 1 为 {{1 }}。

答案 1 :(得分:0)

def vertical_win(game):
    for column in range(3):
        score = sum(row[column] for row in game)
        if score == 0 or score == 3:
            print("Winner")

答案 2 :(得分:0)

您可以编写以下内容:

def vertical_win(game):
    # looping over all the items in the first item of the game
    for column in range(len(game[0])):
        # going over all the other games, and checking if they have the same values in a certain column
        for other in range(1, len(game)):
            # if they don't have the same value in a column break, since it won't be necessary to check
            # if all the items in game have the same value in a specific column, that
            # means that there will be no breaks so the else statement will run
            if game[0][column] != game[other][column]:
                break
        else:
            # return True if didn't break out of loop
            return True
    # return False if we didn't return True at any time
    return False

该函数在垂直获胜时返回 true,并且它对游戏的大小也是完全动态的,因此它甚至可以在 4x4 网格上运行。此外,如果您愿意,您可以通过在返回 True 时将 column 与已经返回的值一起返回来知道获胜发生在哪个索引中。