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. 但是,我正在尝试使用字节码级别跟踪进行一些动态分析。像下面这样的循环使用iterators进行迭代。我需要跟踪迭代器正在访问的索引。尽管应该有一些变通方法,例如,在分析程序中显式地跟踪索引,但类似的功能next_index(it)会使其变得容易且不易出错。

l = [0,1,2,3,4]
for c in l:
    print(c)
4

1 回答 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
于 2019-04-11T03:38:59.323 回答