我有一个我希望在两个级别迭代的生成器。第一级是不均匀的间隔,然后我想将下一级别分成5组,比方说。我需要它以节省内存并处理生成器输入,所以我正在做类似以下的事情。我不得不认为可能有更好的方法吗?特别是,我不希望在不均匀的长度结果中跟踪Nones。
import itertools
def dynamic_grouper(iterable, intervals):
for i in intervals:
inner_iter = list(itertools.islice(iterable, i)) # this is a "group"
yield inner_iter
iterable = iter(xrange(100))
chunk_sizes = [22,30,38,10]
for i,group in enumerate(dynamic_grouper(iterable, chunk_sizes)):
args = [iter(group)] * 5
for item in itertools.izip_longest(fillvalue=None, *args):
print "Group %i" % i
print "Items %s" % list(item)
答案 0 :(得分:5)
要避免使用None
,您可以使用chunks:
def chunks(seq, n):
# https://stackoverflow.com/a/312464/190597 (Ned Batchelder)
""" Yield successive n-sized chunks from seq."""
for i in xrange(0, len(seq), n):
yield seq[i:i + n]
for i,group in enumerate(dynamic_grouper(iterable, chunk_sizes)):
for item in chunks(group, 5):
print "Group %i" % i
print "Items %s" % list(item)