Add code from lecture about iterators

main
Aleksey Zubakov 2 years ago
parent 06193bafba
commit 3ff9dee64a
  1. 2
      09_python/dict_gen.py
  2. 9
      09_python/enum.py
  3. 36
      09_python/for_loop.py
  4. 9
      09_python/func_stream.py
  5. 17
      09_python/gen.py
  6. 20
      09_python/lzy_load.py

@ -0,0 +1,2 @@
a = {k: k * 379 for k in range(10)}
print(a)

@ -0,0 +1,9 @@
els = ["a", "b", "c"]
def _enum(els):
return zip(range(len(els)), els)
for idx, el in _enum(els):
print(idx, el)

@ -0,0 +1,36 @@
class IterableStack:
def __init__(self):
self._lst = [1, 2, 3, 4, 5]
def __iter__(self):
return ReverseIterator(self._lst)
class ReverseIterator:
def __init__(self, _lst):
self._lst = _lst
self.position = len(_lst)
def __next__(self):
self.position -= 1
if self.position < 0:
raise StopIteration()
return self._lst[self.position]
# container = IterableStack()
# for v in container:
# print(v)
container = IterableStack()
it_container = iter(container) # container.__iter__()
while True:
try:
v = next(it_container) # it_container.__next__()
# тело фора
print(v)
# конец тела фора
except StopIteration:
break

@ -0,0 +1,9 @@
def local_gen():
n = 0
def next():
nonlocal n
n += 1
return n
return next

@ -0,0 +1,17 @@
def _range(start, stop):
assert start < stop
def inside_gen():
nonlocal start
while start < stop:
print("Going to return: ", start)
yield start
start += 1
print("here")
return inside_gen()
# for el in _range(0, 10):
# print(el)

@ -0,0 +1,20 @@
from typing import List
def load_files(paths: List[str]):
for path in paths:
with open(path) as f:
yield f.readlines()
paths = [
"dict_gen.py",
"enum.py",
"for_loop.py",
"gen.py",
"lzy_load.py",
]
for cont in load_files(paths):
# code working with content
print(cont)
Loading…
Cancel
Save