【Python】生成器和递归

l=[1, 2, 3, 4, 5, 6]

如果l求和,毫无疑问可以使用递归,比如可以这样:

1 def sum(l):
2     res = 0
3     for i in l:
4         if not isinstance(i, list):
5             res+=i
6         else:
7             res+=sum(i)
8     return res

如果我们想把l中的所有子列表裂解开,这种方法行不行。。。?比如可以这样

方法1:

 1 def play(l):
 2     res = []
 3     for i in l:
 4         if isinstance(i, list):
 5             t=list(play(i))
 6             for j in t:
 7                 res.append(j)
 8         else:
 9             res.append(i)
10     return res

如果使用生成器的话:

方法2

1 def play2(l):
2     try:
3         for i in l:
4             for num in play2(i):
5                 yield num
6     except TypeError:
7         yield l

可以看到方法2看起来简单了很多,但是方2都有一个问题,如果有一个列表是这样的

l2=['abs',['de','fg',['hi','jk']]]

那么方法2还可行吗?

这是方法2的输出结果:

方法2进入了无限递归。。。因为字符串不会引起Type Error

那该怎么办?

 1 def play3(l):
 2     try:
 3         try: l+''
 4         except TypeError: pass
 5         else: raise TypeError
 6         for i in l:
 7             for s in play3(i):
 8                 yield s
 9     except TypeError:
10         yield l

用一个简单的l+''检查是否为字符串,如果l是字符串的话,进入else引起Type Error,然后yield l

如果l不是字符串,则什么都不干,进入下面的for循环。

很有意思的用法

原文地址:https://www.cnblogs.com/fcyworld/p/6214918.html