您需要“返回”,或者在这种情况下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)
which 创建生成器,但仅循环生成器会导致它执行生成器函数以生成项目。
演示:
>>> 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