Search code examples
pythonlistcontains

search in a multidimensional list in python


I have a list of tuples, namely F = [(1,2,1), (2,3,0), (1,2,4)].

If I want to check whether (1,2,1) exists in the F I use F.__contains__((1,2,1)).

But how can I check whether (1,2,just any number) or (1,just any number,just any number) exists in the list?

I used F.__contains__((1,2,True)) but didn't work correctly.


Solution

  • In a comment Mohammad asked for a more generic search method. Here's one way to do it.

    from itertools import zip_longest
    
    F = [(1,2,1), (2,3,0), (1,2,4)]
    
    def search_2d_list(needle, haystack):
        def equal_or_none(row):
            return all(q is None or q == i for q, i in zip_longest(needle, row))
        return any(equal_or_none(row) for row in haystack)
    

    Results from terminal

    >>> search_2d_list((1,), F)
    True
    >>> search_2d_list((1,2), F)
    True
    >>> search_2d_list((1,2,1), F)
    True
    >>> search_2d_list((1,2,3), F)
    False
    >>> search_2d_list((2,2,3), F)
    False
    >>> search_2d_list((2,2), F)
    False
    >>> search_2d_list((2,None,2), F)
    False
    >>> search_2d_list((2,None,0), F)
    True