How do I check if a list is a subset of a bigger 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
How do I check if a list is a subset of a bigger 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
>>> 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
mostly like the other answers, but I do prefer the generator syntax here, seems more natural and it's lazily evaluated:
if all(x in b for x in a):
pass
if you care about the number of repeated elements, this option seems nice, and you could optimize it 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