本文介绍了itertools中的izip_longest:迭代器中的indexError如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在问题中@lazyr询问以下内容来自,没有使用过哨兵。
in izip_longest_next
in the code of izip_longest
, no sentinel is used.
相反,CPython会跟踪有多少迭代器仍然在计数器处于活动状态,并在活动数量达到零时停止。
Instead, CPython keeps track of how many of the iterators are still active with a counter, and stops when the number active reaches zero.
如果发生错误,它将结束迭代,就像没有迭代器仍处于活动状态一样,并允许要传播的错误。
If an error occurs, it ends iteration as if there are no iterators still active, and allows the error to propagate.
代码:
item = PyIter_Next(it);
if (item == NULL) {
lz->numactive -= 1;
if (lz->numactive == 0 || PyErr_Occurred()) {
lz->numactive = 0;
Py_DECREF(result);
return NULL;
} else {
Py_INCREF(lz->fillvalue);
item = lz->fillvalue;
PyTuple_SET_ITEM(lz->ittuple, i, NULL);
Py_DECREF(it);
}
}
我看到的最简单的解决方案:
The simplest solution I see:
def izip_longest_modified(*args, **kwds):
# izip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
fillvalue = kwds.get('fillvalue')
class LongestExhausted(Exception):
pass
def sentinel(counter = ([fillvalue]*(len(args)-1)).pop):
try:
yield counter() # yields the fillvalue, or raises IndexError
except:
raise LongestExhausted
fillers = repeat(fillvalue)
iters = [chain(it, sentinel(), fillers) for it in args]
try:
for tup in izip(*iters):
yield tup
except LongestExhausted:
pass
这篇关于itertools中的izip_longest:迭代器中的indexError如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!