Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested 'any' and 'all' condition in Python

Tags:

python

I have a list of lists

list1 = [['a','b','c'],['m','n','o'],['x','y','z']]

Now, I want to check if all elements of any one of these 'sub-lists' are present in an incoming list called list2.

For example, if

list2 = ['a','c','e','b'] #Code would return True as a,b,c all from list1[0] match
list2 = ['a','c','m','x','e'] # False as all elements from any one sub-list do not match
list2 = ['g','h','i','x','y','z'] # True as all elements from list1[2] matched

I know that this can be done using a nested all within any python function. If list1 was not a nested list, I would have used

result = any(elem in list2 for elem in list1) # To check for any one

or

result = all(elem in list2 for elem in list1) # To check for all

However, I am at loss to do a nested any/all type of list comprehension. Any guidance would be appreciated.

like image 620
Rishi Mehta Avatar asked Nov 15 '25 18:11

Rishi Mehta


2 Answers

You can do a combination of any and all:

list1 = [['a','b','c'],['m','n','o'],['x','y','z']]

def test(l1, l2):
    return any(all(x in l2 for x in sub) for sub in l1)

print(test(list1, ['a','c','e','b']))
print(test(list1, ['a','c','m','x','e']))
print(test(list1, ['g','h','i','x','y','z']))

Output:

True
False
True

The test means: if all x's of any of the sublists are in list2.

like image 125
MrGeek Avatar answered Nov 17 '25 08:11

MrGeek


Why not make list2 a set and use set.issuperset to see if all elements are in list2

list2 = {'g','h','i','x','y','z'}
print(any(list2.issuperset(elem) for elem in list1))
#True

You can even make this more simple using map although the comprehension is more readable

any(map(list2.issuperset, list1))

If you go this route I suggest not using list2 as the name to avoid confusion

like image 41
Jab Avatar answered Nov 17 '25 09:11

Jab



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!