在Python中按(n)块迭代迭代器?

Iterate an iterator by chunks (of n) in Python?(在Python中按(n)块迭代迭代器?)
本文介绍了在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]chunks(l,3) 成为迭代器 [1,2,3], [4,5,6], [7]

Therefore l=[1,2,3,4,5,6,7] with chunks(l,3) becomes an iterator [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 文档的 grouper() 配方.python.org/3/library/itertools.html#itertools-recipes" rel="nofollow noreferrer">recipes 接近你想要的:

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 and 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)块迭代迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

python: iterating through a dictionary with list values(python:遍历具有列表值的字典)
What is the difference between chain and chain.from_iterable in itertools?(itertools中chain和chain.from_iterable有什么区别?)
python JSON only get keys in first level(python JSON只获取第一级的键)
Iterate over n successive elements of list (with overlapping)(迭代列表的 n 个连续元素(重叠))
Loop problem while iterating through a list and removing recurring elements(遍历列表并删除重复元素时出现循环问题)
Elegant way to skip elements in an iterable(跳过可迭代元素的优雅方式)