繁体   English   中英

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

[英]Find matching elements on the same index in a list of lists?

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

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

我正在尝试以下 function:

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")

Output:

Winner
Winner
Winner

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

获取游戏板“列”的一种简单方法是使用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]

对于所有三个迭代,boolean 表达式if check.count(check[0]) == len(check) and check[0] != 0对于这个特定的板 state 总是为真,因为check[0] == 1check.count(1) == len([1])check[0] == 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")

您可以编写以下内容:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM