Pregunta

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 it in one row without a for loop for example?

Thanks!

¿Fue útil?

Solución

You probably want any:

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

Some sort of loop is inevitable though.

Otros consejos

You could use itertools.chain like that :

from itertools import chain

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

print 4 in chain(*nested__seq)

PS : you shouldn't override bultins like "list"

It's abusive, but you can do this in one line pretty 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

If you have a list of iterables with arbitrary depth, flatten it first:

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)

Prints:

True
True
False

You could also do this with in

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

EDIT: this method check only if foo is as fist element.

To search as 'foo' a element (any):

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

Some more try:

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top