在Python中用块(n)迭代迭代器? [英] Iterate an iterator by chunks (of n) in Python?

查看:279
本文介绍了在Python中用块(n)迭代迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能想出一个很好的方法(可能用itertools)将迭代器拆分成给定大小的块吗?

Can you think of a nice way (maybe with itertools) to split an iterator into chunks of given size?

因此 l = [ 1,2,3,4,5,6,7] 块(l,3)成为迭代器 [1,2,3],[4,5,6],[7]

我能想到一个小程序要做这可能不是一个很好的方式,可能是itertools。

I can think of a small program to do that but not a nice way with maybe itertools.

推荐答案

石斑鱼()来自 itertools 文档的配方食谱接近你想要的:

The grouper() recipe from the itertools documentation's recipes comes close to what you want:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

它会填充最后一个带有填充值的块。

It will fill up the last chunk with a fill value, though.

一种不常用的解决方案序列,但确实处理最后一个块是

A less general solution that only works on sequences but does handle the last chunk as desired is

[my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]

最后,适用于一般迭代器的解决方案的行为符合要求是

Finally, a solution that works on general iterators an behaves as desired is

def grouper(n, iterable):
    it = iter(iterable)
    while True:
       chunk = tuple(itertools.islice(it, n))
       if not chunk:
           return
       yield chunk

这篇关于在Python中用块(n)迭代迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆