将我的生成器转换为生成器理解
Convert my generator to a generator comprehension
函数式编程忍者的问题。这是我的发电机:
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)
您的代码无效,因为
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))
函数式编程忍者的问题。这是我的发电机:
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)
您的代码无效,因为
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))