2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Pythonでイテレータの先読みやPushBackをするには

Posted at

イテレータの先読みやPushBackをするにはmore-itertoolsのpeekableが便利だとわかったのでメモ

[1, 1, 2, 4, 4, 4, 1, 2, 2, 4, 4, 5, 5]

[[1, 1], [2], [4, 4, 4], [1], [2, 2], [4, 4], [5, 5]]
になるように、連続する要素をまとめるコード例

peek.py
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))

peek関数は引数に何も入れない場合、最後に(先のアイテムがなくて読み込めないとき)例外出すので番兵(sentinel)を置いています。

2
6
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?