我的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)我的问题是,为什么我会得到一个StopIteration错误?当我在一个小数据集中测试这个公式时,它工作得很好,没有任何问题。但是,当我将它应用于较大的数据集时,会出现异常。
它说问题在list_of_iteration.append(next(i))线上
我做错了什么?
这些是堆栈跟踪:
File "XXXXXXXXXXXXXXXX", line 19, in subset_sum
list_of_iteration.append(next(i))
StopIterationKeyboardInterrupt
发布于 2022-03-31 23:06:25
变量"itr“必须为空。如果尝试在空迭代器上执行next()循环(),就会得到一个StopIteration。试试这个:
empty = []
i = cycle(empty)
print(next(i))发布于 2022-03-31 23:05:31
StopIteration错误是在迭代器中没有调用next的下一个元素时从next方法抛出的异常。
在您的代码中,迭代器i的元素必须少于rounds值所需的元素。
https://stackoverflow.com/questions/71699991
复制相似问题