首页 > 解决方案 > 替代 next(next(...)) 来访问迭代器的第 n 个元素

问题描述

我有一个children 等效于<list_iterator object at 0x050BAAF0>(VS 代码调试器)的列表迭代器,并且需要访问该迭代器的第 4 个元素,我知道它肯定存在。

有没有一种快速的方法,而不是调用 4 次next(children)来访问列表迭代器中第 n 个位置的元素,而无需列表本身。

谢谢!

编辑:这里是一些代码:迭代器实际上是一个 BeautifulSoup 节点的子节点div

virgin_url = "https://www.clicpublic.be/product/_"
product_soup = get_soup(virgin_url + single_id + ".html") 
#get_soup returns the BeatutifulSoup([HTML of page])
bs_info_list = product_soup.findAll("div", {'class': "txtProductInformation"}
children = bs_info_list[0].children

标签: pythoniterator

解决方案


you can use itertool.islice:

from itertools import islice

next(islice(children, 3, None))

The 4th element has index 3

ex:

from itertools import islice

children = (e for e in range(100))
next(islice(children, 3, None))

output:

3

推荐阅读