问题描述
在 C++ 中,我可以使用取消引用访问迭代器 it
指向的值以及周围的值(这并不总是安全的,但这里的主题不相关):std::cout << "prev: " << *(it-1) << ",here: " << *it << ",next: " << *(it+1) << std::endl;
>
我如何在 Python 中做同样的事情?
使用 next()
我可以获得当前值,但这也会增加迭代器(类似于 C++ *it++
)。
完整的代码示例如下:
#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) << ",next: " << *(it+1) << std::endl;
}
return 0;
}
解决方法
你不能这样做,但有一些使用 import requests
from bs4 import BeautifulSoup as soup
my_url = "https://www.money.pl/gielda/gpw/akcje/"
headers = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/87.0.4280.141 Safari/537.36")
page = requests.get(my_url,headers=headers,timeout=10)
page_soup = soup(page.text,'lxml')
的解决方法,例如
itertools
或者重建迭代器:
>>> from itertools import tee
>>> it = iter([1,2,3])
>>> it,it2 = tee(it)
>>> next(it2)
1
>>> list(it)
[1,3]