我花了很多时间在这个问题上没有找到任何提示......我不明白为什么屈服禁止我的递归函数执行,没有任何输出。
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
有关何处/寻找什么的提示?
答案 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
来测试str
和unicode
:
if isinstance(l, basestring):
# either a str or a unicode value