开发者

Python not all in operation

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


http://docs.python.org/library/stdtypes.html#set.issubset

set(a).issubset(set(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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜