Debian 为什么';来自'的收益率;需要一个封闭的';而1';?
我试图理解“收益率来源”是如何使用的。为此,我编写了一个简单的(相当无用的) 示例(count_vorels.py),运行时在其下方生成:Debian 为什么';来自'的收益率;需要一个封闭的';而1';?,debian,python-3.5,yield-from,Debian,Python 3.5,Yield From,我试图理解“收益率来源”是如何使用的。为此,我编写了一个简单的(相当无用的) 示例(count_vorels.py),运行时在其下方生成: $ python3 count_vowels.py Counter({'a': 5}) 请解释为什么proxy2函数(委托生成器)中需要“while True” 没有“while True”: $ python3 count_vowels.py Traceback (most recent call last): File "count_vowel
$ python3 count_vowels.py
Counter({'a': 5})
请解释为什么proxy2函数(委托生成器)中需要“while True”
没有“while True”:
$ python3 count_vowels.py
Traceback (most recent call last):
File "count_vowels.py", line 39, in <module>
main()
File "count_vowels.py", line 34, in main
p.send(None)
StopIteration
使用Python 3.5.3、Debian GNU/Linux 9.8(stretch)
更新:Windows7,Python 3.7.2,结果相同
更新:05/04
p、 在proxy2中不带“while True”的send(None)将引发StopIteration。我修改了
proxy2:
同样,我看不出有什么解释,但它是有效的
更新04/05
我一直在试验和研究文档。下面(IMHO)是我认为正确的代码。我从proxy2中删除了多余的“收益率”
def counter2(cnt):
while True:
c = yield
if c is None:
break
if isinstance(c, (str)) and (str.upper(c) in VOWELS):
cnt[c] += 1
return cnt
def proxy2(cnt):
tmp = yield from counter2(cnt)
return tmp
def main():
word = 'abracadabra'
cnt = Counter()
p = proxy2(cnt)
next(p)
for c in word:
p.send(c)
try:
p.send(None)
except StopIteration as exc:
res = exc.value
print(res)
我一直在学习政治公众人物380。我不能说我找到了上面代码的确认
def proxy2(cnt):
tmp = yield from counter2()
cnt.update(tmp)
yield
def counter2(cnt):
while True:
c = yield
if c is None:
break
if isinstance(c, (str)) and (str.upper(c) in VOWELS):
cnt[c] += 1
return cnt
def proxy2(cnt):
tmp = yield from counter2(cnt)
return tmp
def main():
word = 'abracadabra'
cnt = Counter()
p = proxy2(cnt)
next(p)
for c in word:
p.send(c)
try:
p.send(None)
except StopIteration as exc:
res = exc.value
print(res)