Skip to content

Instantly share code, notes, and snippets.

@kurogelee
Created September 8, 2018 04:25
Show Gist options
  • Save kurogelee/c8ee262e3c1bcf9b59e01a3a0bab07de to your computer and use it in GitHub Desktop.
Save kurogelee/c8ee262e3c1bcf9b59e01a3a0bab07de to your computer and use it in GitHub Desktop.
Pythonでイテレータの先読みやPushBackをするには ref: https://qiita.com/kurogelee/items/654e6083d37c4259d42d
from typing import TypeVar, Iterable, Generator, List
from more_itertools import peekable
T = TypeVar("T")
Gen = Generator[T, None, None]
def partition(items: Iterable[T]) -> Gen[List[T]]:
items = peekable(items)
result = []
sentinel = object()
for item in items:
next_item = items.peek(sentinel)
result.append(item)
if item != next_item:
yield result
result = []
parted = partition([1, 1, 2, 4, 4, 4, 1, 2, 2, 4, 4, 5, 5])
print(list(parted))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment