从可迭代对象一次生成多个对象?
如何从可迭代对象中一次生成多个项目?
例如,对于任意长度的序列,如何在每次迭代的 X 个连续项目组中迭代序列中的项目?
How can I yield multiple items at a time from an iterable object?
For example, with a sequence of arbitrary length, how can I iterate through the items in the sequence, in groups of X consecutive items per iteration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题有点模糊,但请查看
itertools
文档中的grouper
配方。(使用
[iter(iterable)]*n
多次压缩同一个迭代器是一个老技巧,但将其封装在此函数中可以避免代码混乱,并且它与许多人会的完全相同的形式和接口这是一种常见的需求,但遗憾的是它实际上并不在itertools
模块中。)Your question is a bit vague, but check out the
grouper
recipe in theitertools
documentation.(Zipping the same iterator several times with
[iter(iterable)]*n
is an old trick, but encapsulating it in this function avoids confusing code, and it is the same exact form and interface many people will use. It's a somewhat common need and it's a bit of a shame it isn't actually in theitertools
module.)这是另一种适用于没有 izip_longest 的旧版 Python 的方法:
无填充符,因此最后一组的元素可能少于 n 个。
Here's another approach that works on older version of Python that don't have izip_longest:
No filler, so the last group might have fewer than n elements.