Last active
August 29, 2015 14:14
-
-
Save tomoh1r/b0fb800687d94a1a5c34 to your computer and use it in GitHub Desktop.
each_slice.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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