简体   繁体   English

如何获取 Python 迭代器的当前值 - 取消引用迭代器而不增加

[英]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;在 C++ 中,我可以访问迭代器指向的值it以及周围的值(这并不总是安全的,但这里不是主题),使用取消引用: std::cout << "prev: " << *(it-1) << ", here: " << *it << ", next: " << *(it+1) << std::endl;

How do I do the same in Python?我如何在 Python 中做同样的事情?

Using next() I can get the current value, but that also increments the iterator (similar to C++ *it++ ).使用next()我可以获得当前值,但这也会增加迭代器(类似于 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你不能这样做,但有一些使用itertools的解决方法,例如

>>> 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:您可以在此处使用zip进行移位:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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