是一个简短的语法连接列表列表到一个单一的列表(或迭代器)在python?

例如,我有一个列表,如下所示,我想迭代a,b和c。

x = [["a","b"], ["c"]]

我能想到的最好的是如下。

result = []
[ result.extend(el) for el in x] 

for el in result:
  print el

当前回答

如果你需要一个列表,而不是一个生成器,使用list():

from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))

其他回答

对于无限嵌套的元素,这是递归工作的:

def iterFlatten(root):
    if isinstance(root, (list, tuple)):
        for element in root:
            for e in iterFlatten(element):
                yield e
    else:
        yield root

结果:

>>> b = [["a", ("b", "c")], "d"]
>>> list(iterFlatten(b))
['a', 'b', 'c', 'd']

这就是所谓的扁平化,有很多实现。

这个怎么样,尽管它只适用于1级深嵌套:

>>> x = [["a","b"], ["c"]]
>>> for el in sum(x, []):
...     print el
...
a
b
c

从这些链接中,显然最完整的-fast-elegant-etc实现如下:

def flatten(l, ltypes=(list, tuple)):
    ltype = type(l)
    l = list(l)
    i = 0
    while i < len(l):
        while isinstance(l[i], ltypes):
            if not l[i]:
                l.pop(i)
                i -= 1
                break
            else:
                l[i:i + 1] = l[i]
        i += 1
    return ltype(l)

遗憾的是,Python没有一个简单的方法来平展列表。试试这个:

def flatten(some_list):
    for element in some_list:
        if type(element) in (tuple, list):
            for item in flatten(element):
                yield item
        else:
            yield element

它将递归地将列表平展;你可以这样做

result = []
[ result.extend(el) for el in x] 

for el in flatten(result):
      print el
flat_list = []
map(flat_list.extend, list_of_lists)

最短!

总是有reduce(不推荐使用functools):

>>> x = [ [ 'a', 'b'], ['c'] ]
>>> for el in reduce(lambda a,b: a+b, x, []):
...  print el
...
__main__:1: DeprecationWarning: reduce() not supported in 3.x; use functools.reduce()
a
b
c
>>> import functools
>>> for el in functools.reduce(lambda a,b: a+b, x, []):
...   print el
...
a
b
c
>>>

不幸的是,用于列表连接的加号操作符不能用作函数——或者幸运的是,如果为了提高可见性,您希望lambdas变得更丑一些。