Project:
python
Python,
pasted
on Jan 5:
|
import collections
def gen_first(lst, n=1, guard=lambda x:True):
returned = False
for el in lst:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for subelement in gen_first(el):
if guard(subel):
yield subel
else:
if not returned and guard(el):
returned = True
yield el
def first(lst, n=1, guard=lambda x:True):
''' list, number, function -> object
return the first item(s) in a list (map compatible) '''
return list(gen_first(lst=lst, n=n, guard=guard))
print(first([1,2,3]))
|
Output:
|
Traceback (most recent call last):
Line 21, in <module>
print(first([1,2,3]))
Line 18, in first
return list(gen_first(lst=lst, n=n, guard=guard))
Line 6, in gen_first
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
AttributeError: 'module' object has no attribute 'Iterable'
|
|