python中的不均匀分块 [英] Uneven chunking in python

查看:126
本文介绍了python中的不均匀分块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出块大小的列表,如何将可迭代对象划分为可变长度的块?我试图哄骗 itertools.islice 却没有成功。

Given a list of chunk sizes, how would you partition an iterable into variable-length chunks? I'm trying to coax itertools.islice without success yet.

for chunk_size in chunk_list: 
   foo(iter, chunk_size)


推荐答案

您需要创建一个可迭代的 iter 对象,以便可以使用特定的对象对其调用 islice 大小,然后从下一次迭代中停下来的地方开始。这是生成器函数的完美用法:

You need to make an iter object of your iterable so you can call islice on it with a particular size, and pick up where you left off on the next iteration. This is a perfect use for a generator function:

def uneven_chunker(iterable, chunk_list):
    group_maker = iter(iterable)
    for chunk_size in chunk_list:
        yield itertools.islice(group_maker, chunk_size)

示例:

>>> iterable = 'the quick brown fox jumps over the lazy dog'
>>> chunk_size = [1, 2, 3, 4, 5, 6]
>>> for item in uneven_chunker(iterable, chunk_size):
...     print ''.join(item)
...
t
he
 qu
ick
brown
 fox j

这篇关于python中的不均匀分块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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