给定一个包含许多单词的字符串,我想颠倒单词的顺序。如果输入是Thanks for all the fish,那么输出应该是fish the all for Thanks。在
我试图用生成器来解决这个问题,以避免创建新的列表。
我想出了以下解决方案:from itertools import islice
def foo(s, begin, end):
for elem in islice(s, begin, end):
yield elem
def baz(s):
i = len(s)
j = len(s)
while True:
i -= 1
if i == -1:
foo(s, i+1, j)
break
if s[i] == ' ':
foo(s, i+1, j)
yield ' '
j = i
s = "Thanks for all the fish"
g = baz(s)
for x in g: print(x, end='')
但是,这段代码的输出是" "(一个只有空格的字符串)。在
另一方面,如果我直接print元素而不是生成它们,它会起作用:
^{pr2}$
这是有效的,并且有as输出fish the all for Thanks。但我不想只是能够打印它,我想有一个正确的发电机。在
最后,我发现,如果避免调用foo,它也可以工作:from itertools import islice
def baz(s):
i = len(s)
j = len(s)
while True:
i -= 1
if i == -1:
for elem in islice(s, i+1, j):
yield elem
break
if s[i] == ' ':
for elem in islice(s, i+1, j):
yield elem
yield ' '
j = i
s = "Thanks for all the fish"
g = baz(s)
for x in g: print(x, end='')
它的输出是fish the all for Thanks。
这个版本提供了我想要的(一个正确的生成器),但是我在它的函数中重复代码。在
我红了栈交换线程关于yield的作用,但我可能理解错了。
在下一个函数结束之前,生成器会发现什么。
这个问题让我觉得这并不是它的工作原理,但除此之外,我是个无能的人。在
如何使用第一个代码片段中的助手函数来解决这个问题?