I am perfectly aware of that..
sample=[[1,[1,0]],[1,1]]
[1,[1,0]] in sample
This will return True.
But what I want to do here is this.
sample=[[1,[1,0]],[1,1]]
[1,0] in sample
I want the return to be True, but this returns False. I can do this:
sample=[[1,[1,0]],[1,1]]
for i in range(len(sample)):
[1,0] in sample[i]
But I am wondering if there is any better or efficient way of doing it.
you can use chain from itertools to merge the lists and then search in the returned list.
>>> sample=[[1,[1,0]],[1,1]]
>>> from itertools import chain
>>> print [1,0] in chain(*sample)
True
A recursive solution that would work for arbitrary (max recursion depth aside) deep nesting. Also works if any elements of the outermost list are not iterables themselves.
from functools import partial
def contains_nested(some_iterable, elmnt):
try:
if elmnt in some_iterable:
return True
except TypeError: # some_iterable is not iterable
return False
else:
return any(map(partial(contains_nested, elmnt=elmnt), some_iterable))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With