Python not everything works

How to check if a list is a subset of a larger list.

i.e.

a = [1,2,3] is a subset of b = [1,2,3,4,5,6]

Can i do something like

if a all in b
+3
source share
3 answers
>>> a = set([1, 2, 3])
>>> b = set([1, 2, 3, 4, 5, 6])
>>> a.issubset(b)
True

or

>>> a = [1, 2, 3]
>>> b = [1, 2, 3, 4, 5, 6]
>>> all(map(lambda x: x in b, a))
True
>>> a = [1, 2, 3, 9]
>>> all(map(lambda x: x in b, a))
False

or (if the number of elements is important)

>>> a = [1, 1, 2, 3]
>>> all(map(lambda x: a.count(x) <= b.count(x), a))
False
+5
source
+12
source

basically similar to other answers, but I prefer the generator syntax here, it seems more natural and lazily evaluated:

if all(x in b for x in a):
    pass

if you are worried about the number of repeating elements, this option seems nice, and you can optimize its sorting c and using bisect:

def all_in(a, b)
    try:
        c = b[:]
        for x in a: c.remove[x]
        return True
    except:
        return False
+2
source

Source: https://habr.com/ru/post/1728458/


All Articles