考虑这个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'))
是否可以修改生成器表达式以返回平面列表?
答案 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']