def generator():
for i in range(10):
yield "foo" + "baz"
for i in range(10):
yield "bar" + "baz"
我想制作如下代码:
def baz(s):
for i in range(10):
yield s + "baz"
def generator():
baz("foo")
baz("bar")
但是,此代码的行为方式不同。
如何在生成器中删除包含yield
的重复代码?
P.S。我找到了yield from
。这正是我想要的,但我的项目是在Python 2.7中。
答案 0 :(得分:1)
您可以重新编码以使用itertools
,如下所示:
from itertools import repeat, chain
def generator():
for i in chain(repeat('foobaz', 10), repeat('barbaz', 10)):
yield i
for x in generator():
print x
给你:
foobaz
foobaz
foobaz
foobaz
foobaz
foobaz
foobaz
foobaz
foobaz
foobaz
barbaz
barbaz
barbaz
barbaz
barbaz
barbaz
barbaz
barbaz
barbaz
barbaz
或者作为一个简单的清单:
from itertools import repeat, chain
def generator():
return list(chain(repeat('foobaz', 10), repeat('barbaz', 10)))
print generator()
,并提供:
['foobaz', 'foobaz', 'foobaz', 'foobaz', 'foobaz', 'foobaz', 'foobaz', 'foobaz', 'foobaz', 'foobaz', 'barbaz', 'barbaz', 'barbaz', 'barbaz', 'barbaz', 'barbaz', 'barbaz', 'barbaz', 'barbaz', 'barbaz']
答案 1 :(得分:0)
您可以这样重写:
def baz(s):
for i in range(10):
yield s + "baz"
def generator():
for s in ["foo", "baz"]:
for b in baz(s):
yield b
答案 2 :(得分:0)
Martin的回答,https://stackoverflow.com/a/35286012/901925可以被视为:
def baz(s):
for i in range(4):yield s+'baz'
def g2():
return itertools.chain(baz('foo'),baz('bar'))
In [411]: list(g2())
Out[411]:
['foobaz',
'foobaz',
'foobaz',
'foobaz',
'barbaz',
'barbaz',
'barbaz',
'barbaz']