python 从迭代中生成连续n个大小的块的生成器。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 从迭代中生成连续n个大小的块的生成器。相关的知识,希望对你有一定的参考价值。

from itertools import islice, chain
 
 
def chunks(iterable: iter, n: int) -> iter:
    '''
   Generator that yields successive n-sized chunks from an iterable.
   Each yilded chunk is a generator of size=chunk_size ().
   That means you have to empty (iterate over) current chunk in order to get the right result
   Last chunk will be sized as is and will not be padded with any value.
   ABCDEFGH -> ABC, DEF, GH
   >>> for chunk in chunks(range(25), n=7):
   ...     print(list(chunk))
   [0, 1, 2, 3, 4, 5, 6]
   [7, 8, 9, 10, 11, 12, 13]
   [14, 15, 16, 17, 18, 19, 20]
   [21, 22, 23, 24]
   '''
    iterator = iter(iterable)
    for first in iterator:
        yield chain([first], islice(iterator, n - 1))
 
if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True)

以上是关于python 从迭代中生成连续n个大小的块的生成器。的主要内容,如果未能解决你的问题,请参考以下文章

生成C ++中N个数字中的所有R位数字(组合,迭代)?

如何在 bash 中生成步骤 n 的范围? (生成带增量的数字序列)

E. Count The Blocks

区间处理之分块

连续 ID 块上的 PostgresQL 窗口函数

Python中生成器和迭代器的功能介绍