Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I search a list that is in a nested list (list of list) without loop in Python?

Tags:

python

list

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.

like image 904
Kiwi Lee Avatar asked Feb 14 '16 09:02

Kiwi Lee


2 Answers

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
like image 125
Alexander Oh Avatar answered Oct 04 '22 20:10

Alexander Oh


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))
like image 30
user2390182 Avatar answered Oct 04 '22 20:10

user2390182