Python 将收益率与下一个()一起使用

Python 将收益率与下一个()一起使用,python,python-3.x,Python,Python 3.x,我试图创建一个生成器,将列表中的每一项与文件的每一行连接起来 我的文件/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)

我试图创建一个生成器,将列表中的每一项与文件的每一行连接起来

我的文件
/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
——也就是说,应该有两个循环


@PatrickArtner打错了,修正了是的,是的。这里的大文件没有问题。
for x in mylist:
    with open('/tmp/list') as fh:
        for line in fh:
            yield '-'.join([x, line.strip()])