开发者

How to check if a list is contained inside another list without a loop?

Is there any builti开发者_运维知识库ns to check if a list is contained inside another list without doing any loop?

I looked for that in dir(list) but found nothing useful.


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

if set(a) <= set(b):
    print("a is in b")


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

all(x in superlist for x in sublist)


You might want to use a set

if set(a).issubset(b):
    print('a is contained in b')


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...)


If you want to validate that all the items from the list1 are on list2 you can do the following list comprehension:

all(elem in list1 for elem in list2)

You can also replace list1 and list2 directly with the code that will return that list

all([snack in ["banana", "apple", "lemon", "chocolate", "chips"] for snack in ["chips","chocolate"])

That any + list comprehension can be translated into this for a better understanding of the code

return_value = False
for snack in snacks:
   if snack in groceries:
     return_value = True
   else:
     return_value = False
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜