2

考虑这个 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'))

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

4

1 回答 1

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']
于 2014-07-25T20:34:38.150 回答