列表理解的优雅总结

Elegant summation of list comprehension

列表理解很棒。是否有一种优雅、灵活的方式来进行列表理解,即 将项目相互附加 ,而不是将它们全部放入列表中?

IE,我有一些理解 [func(x) for x in y if z] 吐出 [['a','b'],['c','d'],['e','f']],我可以写什么来代替吐出 ['a','b','c','d','e','f']

显然我可以做到

alist = []

for x in y:
    if z:
        alist += func(x)

但那是四五行代码!感觉必须有一种方法可以像列表理解一样简单易行。

[elem for x in y if z for elem in func(x)]

再加一层迭代就可以了

这个问题不是特定于列表推导;它与一般的嵌套容器或可迭代对象的扁平化有关。 (这将包括 listtupleset 等)

不像一些草率的编程语言 — cough 其名称也以“P”开头 cough — Python 从不 隐式 压平嵌套容器。

标准库 Pythonic 扁平化嵌套容器的方法是使用 itertools.chain,它作为生成器工作,因此避免制作列表的不必要的中间副本,或者您传递的任何可迭代对象它。有两种调用方式:

  • chain(iterable1, iterable2, …):例如,list(chain([1,2],[3,4]))[1, 2, 3, 4]
  • chain.from_iterable(iterable_of_iterables):例如,l = [[1, 2], [3, 4]]; list(chain.from_iterable(l))[1, 2, 3, 4]

对于您的具体示例:

from itertools import chain

# Your starting case:
l = [['a','b'],['c','d'],['e','f']]

# This is now an iterator, not a list
it = chain.from_iterable(l)

# Make it back into a list
l2 = list(it)

# Prints:
#   ['a', 'b', 'c', 'd', 'e', 'f']
print(l2)