Ric*_*ica -2 python list-comprehension python-3.x
函数式编程忍者的问题.这是我的发电机:
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
Run Code Online (Sandbox Code Playgroud)
我怀疑这可能会变成一个生成器表达式.不过,当我尝试制作时,我的头往往会受伤.可能吗?
编辑:这是我的尝试,它没有工作(产生一个生成器对象):
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)
Run Code Online (Sandbox Code Playgroud)
你的代码不起作用,因为
yield (line for line in f if all(search in line for search in searches))
Run Code Online (Sandbox Code Playgroud)
将您的函数转换为生成器,生成另一个生成器(由生成器表达式形成).
你需要的是yield from(Python 3.3+):
yield from (line for line in f if all(search in line for search in searches))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |