可以修改此生成器表达式以匹配循环结果吗?

时间:2014-07-25 20:33:26

标签: python generator-expression

考虑这个for循环:

y = []
for z in ('a', 'b\nc', 'd'):
    y.extend(z.splitlines())

没有类似地获得单位列表y
y = []
y.extend(z.splitlines() for z in ('a', 'b\nc', 'd'))

是否可以修改生成器表达式以返回平面列表?

1 个答案:

答案 0 :(得分:4)

你需要一个双循环:

y.extend(v for z in ('a', 'b\nc', 'd') for v in z.splitlines())

如果y开头为空,您也可以将其列为清单:

y = [v for z in ('a', 'b\nc', 'd') for v in z.splitlines()]

您还可以使用itertools.chain.from_iterable()

from itertools import chain

y.extend(chain.from_iterable(z.splitlines() for z in ('a', 'b\nc', 'd')))

演示:

>>> from itertools import chain
>>> [v for z in ('a', 'b\nc', 'd') for v in z.splitlines()]
['a', 'b', 'c', 'd']
>>> y = []
>>> y.extend(v for z in ('a', 'b\nc', 'd') for v in z.splitlines())
>>> y
['a', 'b', 'c', 'd']
>>> y = []
>>> y.extend(chain.from_iterable(z.splitlines() for z in ('a', 'b\nc', 'd')))
>>> y
['a', 'b', 'c', 'd']