考虑以下程序,从标题开始,它应该是不言自明的。我需要实现函数next_index(it)
,该函数返回迭代器将要返回的下一项的索引。
def next_index(it):
#do something here
#return the index of next element the iterator will fetch
return -1 #dummy value being returned now
l = [0,1,2,3,4]
it = iter(l)
fst = it.__next__()
print(fst) # prints 0, the next call to it.__next__() will return the element at index 1
n_i = next_index(it)
#n_i should be 1
print(n_i)
_ = it.__next__()
n_i = next_index(it)
#n_i should be 2 now
print(n_i)
我知道,迭代器通常在不需要索引时使用,对于索引,我们可以使用enumerate
。但是,我正在尝试使用bytecode级别跟踪进行一些动态分析。使用iterators迭代如下循环。我需要跟踪迭代器正在访问的索引。尽管应该有一些变通办法,例如,明确地跟踪分析过程中的索引,但是类似next_index(it)
的函数将使其变得容易且不易出错。
l = [0,1,2,3,4]
for c in l:
print(c)
答案 0 :(得分:0)
在迭代器中包裹一些东西,以保持计数。
class EnumeratedIter:
def __init__(self, it):
self.it = it
self.index = 0
def __next__(self):
self.index += 1
return next(self.it)
def __iter__(self):
return self
def next_index(it):
return it.index
l = list("abcde")
it = EnumeratedIter(iter(l))
n_i = next_index(it)
assert n_i == 0
next(it)
n_i = next_index(it)
assert n_i == 1
next(it)
n_i = next_index(it)
assert n_i == 2