是否有可能从迭代器获取下一个项的索引?

问题描述 投票:1回答:1

从标题中考虑以下程序,该标题应该是自解释的。我需要实现函数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迭代如下的循环。我需要跟踪迭代器访问的索引。虽然应该有解决方法,例如,明确地跟踪分析prgroam中的索引,像next_index(it)这样的函数会使它变得容易且不易出错。

l = [0,1,2,3,4]
for c in l:
    print(c)
python python-3.x dynamic-analysis
1个回答
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
© www.soinside.com 2019 - 2024. All rights reserved.