简体   繁体   中英

How to get the current value of a Python iterator - dereferencing an iterator without incrementing

In C++ I can access the value pointed to by an iterator it , as well as surrounding ones (which is not always safe, but that's off topic here), using dereference: std::cout << "prev: " << *(it-1) << ", here: " << *it << ", next: " << *(it+1) << std::endl;

How do I do the same in Python?

Using next() I can get the current value, but that also increments the iterator (similar to C++ *it++ ).

Complete code example below:

#include <iostream>
#include <vector>
int main() 
{
    std::vector<int> myvector{ 1, 2, 3, 4, 5 };
    for (auto it = myvector.begin()+1; it != myvector.end()-1; ++it) {
        std::cout << "prev: " << *(it-1) << ", here: " << *it << ", next: " << *(it+1) << std::endl;
    }
    return 0;
}

You can't do it, but there are some workaround using itertools , eg

>>> from itertools import tee
>>> it = iter([1,2,3])
>>> it, it2 = tee(it)
>>> next(it2)
1
>>> list(it)
[1, 2, 3]

Or rebuilding the iterator:

>>> from itertools import chain
>>> it = iter([1,2,3])
>>> first = next(it)
>>> first
1
>>> list(chain([first], it))
[1, 2, 3]

You can use zip for shifting here:

data = [1, 2, 3, 4, 5]
for prev, here, nxt in zip(data, data[1:], data[2:]):
    print(f"prev: {prev}, here: {here}, next: {nxt}")

It will print:

prev: 1, here: 2, next: 3
prev: 2, here: 3, next: 4
prev: 3, here: 4, next: 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM