How to check a list contained by another list without a loop?

前端 未结 4 1765
攒了一身酷
攒了一身酷 2020-12-31 01:33

As the title mentions,is there any builtins to do this job?I looked for that in dir(list) but got no usable one.Thanks.

相关标签:
4条回答
  • 2020-12-31 01:46

    Assuming that you want to see if all elements of sublist are also elements of superlist:

    all(x in superlist for x in sublist)

    0 讨论(0)
  • 2020-12-31 01:47

    Depends on what you mean by "contained". Maybe this:

    if set(a) <= set(b):
        print "a is in b"
    
    0 讨论(0)
  • 2020-12-31 02:04

    the solution depends on what values you expect from your lists.

    if there is the possiblity of a repetition of a value, and you need to check that there is enough values in the tested container, then here is a time-inefficient solution:

    def contained(candidate, container):
        temp = container[:]
        try:
            for v in candidate:
                temp.remove(v)
            return True
        except ValueError:
            return False
    

    test this function with:

    >>> a = [1,1,2,3]
    >>> b = [1,2,3,4,5]
    >>> contained(a,b)
    False    
    >>> a = [1,2,3]
    >>> contained(a,b)
    True
    >>> a = [1,1,2,4,4]
    >>> b = [1,1,2,2,2,3,4,4,5]
    >>> contained(a,b)
    True
    

    of course this solution can be greatly improved: list.remove() is potentially time consuming and can be avoided using clever sorting and indexing. but i don't see how to avoid a loop here...

    (anyway, any other solution will be implemented using sets or list-comprehensions, which are using loops internally...)

    0 讨论(0)
  • 2020-12-31 02:05

    You might want to use a set

    if set(a).issubset(b):
        print('a is contained in b')
    
    0 讨论(0)
提交回复
热议问题