为了标记文件,我有一个生成器,它会抛出文件的空白分隔部分,忽略换行符。
def parts(filename):
file = open(filename, 'r')
for line in file:
for part in line.split():
yield part
现在,我想把它写成一个生成器理解 - 什么不起作用:
p = (part for part in line.split() for line in file)
或
p = (part for part in (line.split() for line in file))
后者吐出分割线而不是分割线的部分
答案 0 :(得分:6)
使用以下语法:
p = (part for line in file for part in line.split())
生成器表达式中最外层的for循环是左边的。
答案 1 :(得分:1)
(word for line in input_file for word in line.split())