Skip to content

Instantly share code, notes, and snippets.

@tomoh1r
Last active Aug 29, 2015
Embed
What would you like to do?
each_slice.py
dummy = object()
def each_slice(lst, number, fill=dummy):
typ = type(lst)
lower, upper = 0, number
while True:
# slice 取ったときに範囲外なら空のリストがとれる
sliced = lst[lower:upper]
if sliced:
if fill == dummy or len(sliced) == number:
# fill が未指定か、切り取ったリストの長さが number ならそのまま返す。
yield sliced
else:
# fill が指定されておりかつ切り取ったリストが number 未満の長さなら fill で埋めて返す
yield sliced + typ([fill for x in range(number - len(sliced))])
lower, upper = upper, upper + number
else:
raise StopIteration()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment