_loop.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from typing import Iterable, Tuple, TypeVar
  2. T = TypeVar("T")
  3. def loop_first(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
  4. """Iterate and generate a tuple with a flag for first value."""
  5. iter_values = iter(values)
  6. try:
  7. value = next(iter_values)
  8. except StopIteration:
  9. return
  10. yield True, value
  11. for value in iter_values:
  12. yield False, value
  13. def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
  14. """Iterate and generate a tuple with a flag for last value."""
  15. iter_values = iter(values)
  16. try:
  17. previous_value = next(iter_values)
  18. except StopIteration:
  19. return
  20. for value in iter_values:
  21. yield False, previous_value
  22. previous_value = value
  23. yield True, previous_value
  24. def loop_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
  25. """Iterate and generate a tuple with a flag for first and last value."""
  26. iter_values = iter(values)
  27. try:
  28. previous_value = next(iter_values)
  29. except StopIteration:
  30. return
  31. first = True
  32. for value in iter_values:
  33. yield first, False, previous_value
  34. first = False
  35. previous_value = value
  36. yield first, True, previous_value