 
                        # _*_ 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))得到的是一个空列表?
求大神指点
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
生成器函数和普通函数有一些不同,看起来
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。
简化如下:
输出:
感觉你是不是想要求something列表里的各个元素加起来和等于27的组合?
这个用yield不太方便在函数内去重吧,是不是要酱紫?
[5, 6, 7, 9]
[4, 6, 8, 9]
[3, 7, 8, 9]
[3, 4, 5, 7, 8]
[3, 4, 5, 6, 9]
[2, 4, 6, 7, 8]
[2, 4, 5, 7, 9]
[2, 3, 6, 7, 9]
[2, 3, 5, 8, 9]
[2, 3, 4, 5, 6, 7]
进程已结束,退出代码0