简体   繁体   English

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

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

I am coding a tic tac toe game the game board looks as follows:我正在编写一个井字游戏,游戏板如下所示:

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

I am trying the following function:我正在尝试以下 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: Output:

Winner
Winner
Winner

it is only iterating over the 0th element of each list.它只遍历每个列表的第 0 个元素。 And if the number it displays winner for a each number per row instead of matching all three numbers of each list.如果数字显示每行每个数字的获胜者,而不是匹配每个列表的所有三个数字。

An easy way to get the "columns" of the game board is to use zip() :获取游戏板“列”的一种简单方法是使用zip()

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

From here you can check for a win with a membership test:从这里您可以通过会员测试检查是否获胜:

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

Putting it together:把它放在一起:

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

You can very easily extend this to larger board sizes with this small modification:通过这个小修改,您可以很容易地将其扩展到更大的电路板尺寸:

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

As for why your code isn't working:至于为什么您的代码不起作用:

>>> 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]

For all three iterations, the boolean expression if check.count(check[0]) == len(check) and check[0] != 0 for this particular board state is always going to be true because check[0] == 1 and check.count(1) == len([1]) and check[0] == 1 which is != 0 .对于所有三个迭代,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")

You could write the following:您可以编写以下内容:

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

The function returns true when there is a vertical win, and it is also completely dynamic to the size of the game, so it could even work on a 4x4 grid. function 在垂直获胜时返回 true,而且它也完全根据游戏大小动态变化,因此它甚至可以在 4x4 网格上运行。 Also, if you want to, you can know in which index the win occurs by returning column together with the already returned value when returning True.此外,如果您愿意,您可以通过在返回 True 时将column与已经返回的值一起返回来知道获胜发生在哪个索引中。

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

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