# _*_ 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)
并没有被忽略,它看起来没有生效的原因还是因为它是一个生成器,对于生成器来说直接把它当作函数来调用是没有效果的,必须对它进行迭代:
elif sum(tempList) > 27:
yield list(fun(tempList))
但我不清楚你这个生成器的实际意义,所以只能给出这样的修改代码了。因为代码中的 fun(tempList)
试图对生成器进行递归调用,这是不行的,生成器只能被迭代,不能直接调用。
关于生成器的递归,可以参考这里的一个例子:http://www.cnblogs.com/youxin/archive/2013/11/17/3428338.html。
简化如下:
def flatten(sequence):
for item in sequence:
if isinstance(item, (list, tuple)):
for subitem in flatten(item):
yield subitem
else:
yield item
something = [1, 2, [3, [], 4, [5, 6], 7, [8]], 9]
for x in flatten(something):
print x
输出:
1
2
3
4
5
6
7
8
9
感觉你是不是想要求something列表里的各个元素加起来和等于27的组合?
这个用yield不太方便在函数内去重吧,是不是要酱紫?
# -*- coding:utf-8 -*-
def func_comb(lst_c, target_num, res=[]):
if lst_c is not None:
for i in xrange(len(lst_c)):
tmp_lst = lst_c[:]
tmp_lst.pop(i)
sum_tmp = sum(tmp_lst)
if sum_tmp == target_num:
if tmp_lst not in res:
res.append(tmp_lst)
elif sum_tmp > target_num:
func_comb(tmp_lst, target_num, res)
else:
pass
return res
if __name__ == '__main__':
list_comb = [2, 3, 4, 5, 6, 7, 8, 9]
target_total = 27
results = func_comb(list_comb, target_total)
for result in results:
print result
[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