从可迭代对象一次产生多个对象? [英] Yield multiple objects at a time from an iterable object?
问题描述
如何从可迭代对象一次产生多个项?
How can I yield multiple items at a time from an iterable object?
例如,对于任意长度的序列,我如何遍历项中的序列,每次迭代X个连续项目的组?
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?
推荐答案
你的问题有点模糊,但看看 grouper
itertools
文档中的食谱。
Your question is a bit vague, but check out the grouper
recipe in the itertools
documentation.
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
(使用 [iter(iterable)] * n
多次压缩相同的迭代器是一个老技巧,但将其封装在此函数中避免了混淆代码,并且它是完全相同的形式很多人都会使用这个界面。这是一个有点普遍的需求,实际上并不是在 itertools $ c $中有点遗憾c>模块。)
(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 the itertools
module.)
这篇关于从可迭代对象一次产生多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!