Alternative for "in" operator for nested lists

If I want to find something in a list in python, I can use the 'in' operator:

list = ['foo', 'bar']
'foo' in list #returns True

But what should I do if I want to find something in a nested list?

list = [('foo', 'bar'), ('bar', 'foo')]
'foo' in list #returns False

Is it possible to do this on one line without a for loop, for example?

Thank!

+5
source share
5 answers

You probably want any:

>>> list = [('foo', 'bar'), ('bar', 'foo')]
>>> any('foo' in e for e in list)
True

However, some kind of loop is inevitable.

+8
source

This is offensive, but you can do it on one line quite easily.

mainlist = [('foo', 'bar'), ('bar', 'foo')]
[elem for elem in sublist for sublist in mainlist] #['bar', 'bar', 'foo', 'foo']

'foo' in [elem for elem in sublist for sublist in mainlist] # True
+2
source

in

>>> list = [('foo', 'bar'), ('bar', 'foo')]
>>> 'foo' in (x[1] for x in list)
True

EDIT: , foo .

'foo' ():

 >>>'foo' in reduce(lambda x,y: x+y, list)   
 True

:

In [7]: list
Out[7]: [('foo', 'me', 'bar'), ('bar', 'foo', 'you')]
In [8]: 'me' in reduce(lambda x,y: x+y, list)
Out[8]: True

In [9]: 'you' in reduce(lambda x,y: x+y, list)
Out[9]: True
+1

, :

import collections 

li= [('foo', 'bar'), ('bar', 'foo'),[[('deeper',('foobar'))]]]

def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
            for sub in flatten(el):
                yield sub
        else:
            yield el

print 'deeper' in flatten(li)  
print 'foo' in flatten(li) 
print 'nope' in flatten(li)

True
True
False
+1

itertools.chain :

from itertools import chain

nested__seq = [(1,2,3), (4,5,6)]

print 4 in chain(*nested__seq)

PS: bultins "list"

+1
source

All Articles