[ create a new paste ] login | about

Project: python
Link: http://python.codepad.org/PxLHuRFx    [ raw code | output | fork ]

Python, pasted on Jan 5:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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:
1
2
3
4
5
6
7
8
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'


Create a new paste based on this one


Comments: