python - 替代 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
解决方案
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
推荐阅读
- android - 在 Ionic 中实现多选功能(长按/按住并选择)
- javascript - html 和 php 文件返回为空
- python - Django - 条件外键
- ms-access-2007 - Access 2007 表单:未绑定文本框:备注字段被截断
- python-3.x - 将 matplotlib.pyplot 导入为 plt - KeyError: 'keymap.quit_all'
- javascript - 获取文本区域的长度
- javascript - React Native Parse.File,我应该将它作为输入提供什么?
- elixir - 长生不老药中的转义字符串
- sql - SQL Server differential backup
- webpack - 如何在 aurelia.json 文件、带有 webpack 捆绑器的应用程序中配置 3rd 方库