Split Sequence by Chunks
def chunk_list(lst, parts=5):
"""Split list to chunks with given size and
return new list with them
:param lst: List from which chunks will be maked
:type lst: list
:param parts: size of the chunks (items from given list in one chunk)
:type parts: int
:return: List with chunks ( [[1,2,3], [4,5,6]] )
:rtype: list
"""
if type(lst) != list:
raise RuntimeError('Invalid parameter specified. Expected type(list) '
'got type({})'.format(type(lst).__name__))
return [lst[x:x+parts] for x in range(0, len(lst), parts)]
# функция для деления последовательности на пачки:
def chunker(seq, size):
chunk = []
for item in seq:
chunk.append(item)
if len(chunk) == size:
yield chunk
del chunk[:]
if chunk:
yield chunk
# используется примерно так:
for chunk in chunker(my_long_list, size=100):
for item in chunk:
# do something...