# _*_ coding:utf_8 _*_
def fun(aList):
for i in range(len(aList)):
tempList = aList[:]
tempList.pop(i)
if sum(tempList) == 27:
yield tempList
elif sum(tempList) > 27:
fun(tempList)
if __name__ == '__main__':
something = [2,3,4,5,6,7,8,9]
for result in fun(something):
print result
请问为什么这个生成器的内容是空的?用list(fun(something))得到的是一个空列表?
求大神指点
生成器函数和普通函数有一些不同,看起来
elif
后面的调用fun(tempList)
整个被忽略了,Python 继续这个for
循环,此时i
变成1,tempList
弹出了第1项,变成 [2, 4, 5, 6, 7, 8, 9] ...其实
fun(tempList)
并没有被忽略,它看起来没有生效的原因还是因为它是一个生成器,对于生成器来说直接把它当作函数来调用是没有效果的,必须对它进行迭代:但我不清楚你这个生成器的实际意义,所以只能给出这样的修改代码了。因为代码中的
fun(tempList)
试图对生成器进行递归调用,这是不行的,生成器只能被迭代,不能直接调用。关于生成器的递归,可以参考这里的一个例子:http://www.cnblogs.com/youxin/archive/2013/11/17/3428338.html。
简化如下:
输出: