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

前端 未结 4 1795
攒了一身酷
攒了一身酷 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 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...)

提交回复
热议问题