-
三国纷争
从Python的itertools文档的recipes部分修改:from itertools import zip_longestdef grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue)示例在伪代码中保持示例简洁。grouper('ABCDEFG', 3, 'x') --> 'ABC' 'DEF' 'Gxx'注意:在Python 2上使用izip_longest而不是zip_longest。
-
吃鸡游戏
def chunker(seq, size): return (seq[pos:pos + size] for pos in range(0, len(seq), size))# (in python 2 use xrange() instead of range() to avoid allocating a list)简单。简单。快速。适用于任何序列:text = "I am a very, very helpful text"for group in chunker(text, 7): print repr(group),# 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'print '|'.join(chunker(text, 10))# I am a ver|y, very he|lpful textanimals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']for group in chunker(animals, 3): print group# ['cat', 'dog', 'rabbit']# ['duck', 'bird', 'cow']# ['gnu', 'fish']
-
慕姐8265434
我是粉丝chunk_size= 4for i in range(0, len(ints), chunk_size):
chunk = ints[i:i+chunk_size]
# process chunk of size <= chunk_size
-
红糖糍粑
import itertoolsdef chunks(iterable,size):
it = iter(iterable)
chunk = tuple(itertools.islice(it,size))
while chunk:
yield chunk
chunk = tuple(itertools.islice(it,size))# though this will throw ValueError if the length of ints# isn't a multiple of four:for
x1,x2,x3,x4 in chunks(ints,4):
foo += x1 + x2 + x3 + x4for chunk in chunks(ints,4):
foo += sum(chunk)其他方式:import itertoolsdef chunks2(iterable,size,filler=None):
it = itertools.chain(iterable,itertools.repeat(filler,size-1))
chunk = tuple(itertools.islice(it,size))
while len(chunk) == size:
yield chunk
chunk = tuple(itertools.islice(it,size))# x2, x3 and x4 could get the value 0 if the length is not# a multiple of 4.for x1,x2,x3,x4
in chunks2(ints,4,0):
foo += x1 + x2 + x3 + x4