最好将递归分离成一个只在以下情况下执行的函数:sum(x for x in iflatten(L) if cond)
其中iflatten是返回flant函数版本的迭代器,cond在您的例子中是type(x) == int and x % 2 == 0。在
^{pr2}$
代码测试如下:L = [1,['a',3,'b',2],[4,['h',8,[10]]], -5]
def iflatten(L):
for i in L:
if isinstance(i, list):
for r in iflatten(i):
yield r
else:
yield i
sum(x for x in iflatten(L) if type(x) == int and x % 2 == 0)
结果是24。在
你不能改变def mult2(n):
if type(n) == int and n%2 ==0:
return n
我们可以将条件从type(x) == int and x % 2 == 0更改为mult2(x) is not None,因为所有函数的末尾都有一个隐式return None。在
我们也来测试一下:L = [1,['a',3,'b',2],[4,['h',8,[10]]], -5]
def iflatten(L):
for i in L:
if isinstance(i, list):
for r in iflatten(i):
yield r
else:
yield i
def mult2(n):
if type(n) == int and n%2 ==0:
return n
sum(x for x in iflatten(L) if mult2(x) is not None)
也会导致24