简体   繁体   English

Python:检查一个数字是否已经在列表列表的网格中

[英]Python: check if a number is already in a grid of list of lists

In Python, I'm trying to create a duplicate checker that can check if the number that I'm entering is already in the grid.在 Python 中,我正在尝试创建一个重复检查器,可以检查我输入的数字是否已经在网格中。 If not present, it should return False .如果不存在,它应该返回False So for example, numbers 1, 8, 9 should return False and others should return True .因此,例如,数字1, 8, 9应该返回False ,而其他数字应该返回True Can someone help me?有人能帮我吗?

grid = [[0, 2, 3],
        [4, 0, 5],
        [6, 7, 0]]


number_rows = len(grid)
def possible(n):
    global grid
    if number_rows == n:
        return False
    return True
    

possible(1)  # ---> True

If the grid is a list of lists you can use a for/else block :如果网格是列表列表,您可以使用for/else 块

def possible(n, grid):
    for x in grid:
        if n in x:
            return False
    else:
        return True

grid = [[0, 2, 3],
        [4, 0, 5],
        [6, 7, 0]]

print(possible(1, grid))  # ---> True
print(possible(2, grid))  # ---> False

Without using packages such as NumPy, the easiest way I can think of is to use Python's any with list comprehension.在不使用 NumPy 之类的包的情况下,我能想到的最简单的方法是使用 Python 的any和列表理解。 Consider something like:考虑类似的事情:

def possible (number, grid):
    check = [number in sublist for sublist in grid]

    return not any(check)

In the function, check will loop through the sublists and return a list of Trues and Falses depending on if number exist in each sublist.在 function 中, check将循环遍历子列表并根据每个子列表中是否存在number返回 True 和 False 列表。 For instance, if you pass 2 as the number , check will be [True, False, False] because 2 only exist in the first sublist.例如,如果您将 2 作为number传递,则check将为[True, False, False]因为 2 仅存在于第一个子列表中。

Then, the any function, like the name suggests, if there are any True s within check .然后, any function,顾名思义,如果在check中有任何True Finally, the not keyword inverts it, since you want the function to return True if there are not already in the "grid".最后, not关键字将其反转,因为如果“网格”中还没有,您希望 function 返回 True。

number_rows = len(grid) only counts the number of lists in the main list grid[a,b,c] . number_rows = len(grid)只计算主列表grid[a,b,c]中的列表数量。 In your code, you're testing if the number you input is equal to the length of the main list.在您的代码中,您正在测试您输入的数字是否等于主列表的长度。 Use the n in list to test if it's true or false.使用n in list来测试它是真还是假。

def possible(n):
    temp = [a for b in grid for a in b] ##put all the values from the grid into a single layer list
    if n in temp: 
        return False
    return True

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

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