函数中引发的停止迭代异常



我的python脚本中有以下函数:

def subset_sum (list_of_int,target):
#create iterable
itr = chain.from_iterable(combinations(list_of_int, n) for n in range(2,len(list_of_int)-1))
#number of iteration rounds
rounds = 1000000
i = cycle(itr)
#instantiate a list where iterations based on number of rounds will be stored
list_of_iteration = []
#loop to create a list of the first n rounds
for x in range(rounds):
list_of_iteration.append(next(i)) 
#find the first list item that = target 
for y in list_of_iteration:
if sum(y) == target: 
return list(y)

我的问题是为什么我会收到停止迭代错误? 当我在一个小数据集中测试这个公式时,它工作正常,没有任何问题。 但是,当我将其应用于较大的数据集时,会出现异常。

它说这个问题符合list_of_iteration.append(next(i))

我做错了什么?

这些是堆栈跟踪:

File "XXXXXXXXXXXXXXXX", line 19, in subset_sum
list_of_iteration.append(next(i))
StopIteration

键盘中断

变量"itr"必须为空。 如果你尝试在一个空迭代器上 next() 一个 cycle(),你会得到一个 StopIteration。 试试这个:

empty = []
i = cycle(empty)
print(next(i))

StopIteration错误是从 当迭代器中没有下一个元素时next方法next被召唤。

在代码中,迭代器i的元素必须少于 由rounds的值要求。

最新更新