Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tomoh1r
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomoh1r/b0fb800687d94a1a5c34 to your computer and use it in GitHub Desktop.
Save tomoh1r/b0fb800687d94a1a5c34 to your computer and use it in GitHub Desktop.
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