关于函数式编程忍者的问题。这是我的发电机:
def get_interesting_line(file,*searches):
with open(file,'r') as f:
for line in f:
if all(search in line for search in searches):
yield line
我怀疑这可能会变成一个生成器表达式。不过,当我尝试制作时,我的头往往会受伤。可能吗?
编辑:这是我的尝试,它没有工作(产生一个生成器对象):def test(file, *searches):
with open(file) as f:
yield (line for line in f if all(search in line for search in searches))
lines = test('myfile')
next(lines)
答案 0 :(得分:6)
您的代码无效,因为
yield (line for line in f if all(search in line for search in searches))
将您的函数转换为生成器,生成另一个生成器(由生成器表达式形成)。
您需要的是yield from
(Python 3.3 +):
yield from (line for line in f if all(search in line for search in searches))