Checking if all elements of a List of Lists are in another List of Lists Python

前端 未结 2 1518
南方客
南方客 2021-01-24 21:37

My question is, how do you check if all of the elements of a list of lists are in another list of lists? Or maybe better phrased, how do you check if one list of lists

相关标签:
2条回答
  • 2021-01-24 21:52

    This is really really easy if you just even tried to see what that piece of code gave you...

    >>> l1 = [1,2]
    >>> l2 = [1,2,3,4,5]
    >>> all(l1)
    True
    >>> [item in l1 for item in l2]
    [True, True, False, False, False]
    >>> help(all)
    Help on built-in function all in module builtins:
    
    all(...)
        all(iterable) -> bool
    
        Return True if bool(x) is True for all values x in the iterable.
        If the iterable is empty, return True.
    

    Anyhow you need to turn them into sets and compute the issubset method

    >>> s1 = set(l1)
    >>> s2 = set(l2)
    >>> s1.issubset(s2)
    True
    

    Edit yes, as others have noted this only works if all the elements of the list are unique and you're not looking for a set math but for an exact match since sets are by default a collection of unique objects.

    0 讨论(0)
  • 2021-01-24 22:01

    Convert your sublists to tuples, for example:

    In [2]: a = [[2,3],[5,6],[8,9]]
    
    In [3]: b = [[2,3],[5,6],[8,9], [10,11]]
    
    In [4]: set(tuple(x) for x in a).issubset(tuple(x) for x in b)
    Out[4]: True
    
    0 讨论(0)
提交回复
热议问题