flatten

In [1]: from compiler.ast import flatten

In [2]: flatten([1, [2], [3, [[4,]]]])
Out[2]: [1, 2, 3, 4]

源代码:

def flatten(seq):
    l = []
    for elt in seq:
        t = type(elt)
        if t is tuple or t is list:
            for elt2 in flatten(elt):
                l.append(elt2)
        else:
            l.append(elt)
    return l

上面方法在python3已经被移除 生成器方法实现:

In [36]: def f(seq):
             for elt in seq:
                 if isinstance(elt, Iterable):
                     for elt2 in f(elt):
                         yield elt2
                 else:
                     yield elt

In [37]:

In [37]: a = f([1,2,[3,4]])

In [38]: l = [x for x in a]

In [39]: l
Out[39]: [1, 2, 3, 4]

In [40]: a
Out[40]: <generator object f at 0x7fead3fca0f8>

扩展求任意嵌套字典{'a': 1,'b':{'c':1,'d':{'e':2,'d':3}}}所有值的和,如1+1+2+3的和为7

def f(d):
    for elt in d.values():
        if isinstance(elt, collections.Iterable):
            for elt2 in f(elt):
                yield elt2
        else:
            yield elt


a = f(d)
l = sum(x for x in a)
print(l)              # 7