Yield语句阻止递归函数?

时间:2013-05-29 07:29:22

标签: python recursion generator yield

我花了很多时间在这个问题上没有找到任何提示......我不明白为什么屈服禁止我的递归函数执行,没有任何输出。

def unlist(l):
    if isinstance(l, unicode) or isinstance(l, str):
        print "This should be printed at least !"
        yield l
    if isinstance(l, list):
        for elem in l:
            unlist(elem)

l = ['a', u'b', 1]

for each in unlist(l): print each

有关何处/寻找什么的提示?

1 个答案:

答案 0 :(得分:3)

您需要'返回',或者在这种情况下yield递归调用的结果:

def unlist(l):
    if isinstance(l, unicode) or isinstance(l, str):
        print "This should be printed at least !"
        yield l
    if isinstance(l, list):
        for elem in l:
            for res in unlist(elem):
                yield res

在这种情况下,yield可能不是绝对必要的,但您需要至少循环通过生成器来执行包含的代码。你只需调用unlist(elem)来创建生成器,但只是循环生成器会导致它执行生成器函数来生成项目。

演示:

>>> def unlist(l):
...     if isinstance(l, unicode) or isinstance(l, str):
...         print "This should be printed at least !"
...         yield l
...     if isinstance(l, list):
...         for elem in l:
...             for res in unlist(elem):
...                 yield res
... 
>>> l = ['a', u'b', 1]
>>> for each in unlist(l): print each
... 
This should be printed at least !
a
This should be printed at least !
b

在Python 3.3及更高版本中,您可以使用yield from语法:

def unlist(l):
    if isinstance(l, unicode) or isinstance(l, str):
        print "This should be printed at least !"
        yield l
    if isinstance(l, list):
        for elem in l:
            yield from unlist(elem)

最后但并非最不重要的是,您可以使用basestring来测试strunicode

if isinstance(l, basestring):
    # either a str or a unicode value