纯新手请教python基础教程中一段代码的问题
菜鸟学习python中,研读Hetland写的python基础教程,其中有一段这个代码
def flat(nested):
try:
try:
nested+""
except TypeError:
pass
else:
raise TypeError
for sublist in nested:
for i in flat(sublist):
yield i
except:
yield nested
nested=["foo",["var",["vazx"]]]
print list(flat(nested))
def flat(nested):
try:
for sublist in nested:
for i in flat(sublist):
yield i
except:
yield nested
nested=["foo",["var",["vazx"]]]
print list(flat(nested))
try:
nested+""
except TypeError:
pass
else:
raise TypeError
[解决办法]
这段代码是在用try...except实现goto。详细解释见注释。
def flat(nested):
try:
try:
nested+"" # 检测nested是否字符串(只有字符串才能和字符串相加,是则转到mark2,否则到mark1
except TypeError:
pass # mark1:是列表,顺序执行到mark3
else:
raise TypeError # mark2:字符串,转到mark4
for sublist in nested: # mark3
for i in flat(sublist):
yield i
except:
yield nested # mark4
nested=["foo",["var",["vazx"]]]
print list(flat(nested))
In [22]: def flat(nested):
...: if type(nested) == str:
...: yield nested
...: else:
...: for sublist in nested:
...: for item in flat(sublist):
...: yield item
In [23]: list(flat(["foo",["var",["vazx"]]]))
Out[23]: ['foo', 'var', 'vazx']