我正在尝试创建一个生成器,将列表中的每一项与文件的每一行连接起来。
我的文件 /tmp/list 包含:
/tmp/list
foo bar
我的代码是:
mylist = [ 'hello', 'world' ] def _gen(): for x in mylist: with open('/tmp/list') as fh: yield('-'.join([x, next(fh)])) for i in _gen(): print(i)
我得到的结果是:
hello-foo world-foo
hello-foo hello-bar world-foo world-bar
你只有一个外环,你只要抓住 第一 next . 但是你需要在 fh 也就是说,应该有 二 循环。
next
fh
for x in mylist: with open('/tmp/list') as fh: for line in fh: yield '-'.join([x, line.strip()])