考虑以下程序,从标题来看,它应该是不言自明的。我需要实现函数 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)
最佳答案
用一些东西包裹迭代器,以记录所产生的结果。
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
关于python - 是否可以从迭代器获取下一项的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55623749/