styleru.py lecture 9

ilebedev

			styleru.py
		

Итераторы и итерируемые

Итерация по спискам

for element in [1, 2, 3, 4]:
    print(element)

Итерация по спискам

for element in [1, 2, 3, 4]:
    print(element)
    
# 1
# 2
# 3
# 4
    

Итерация по строкам

for letter in 'python':
    print(letter)

Итерация по строкам

for letter in 'python':
    print(letter)
    
# p
# y
# t
# h
# o
# n

Итерация по словарям

for key in {'name': Вася, 'is_active': True}:
    print(key)

Итерация по словарям

for key in {'name': Вася, 'is_active': True}:
    print(key)
    
# name
# is_active

Итерация по потокам

for line in open('мемы.txt'):
    print(line)

Итерация по потокам

for line in open('мемы.txt'):
    print(line)
    
# Узбагойся
# Кек

iterator и iterable

iterable

iterator

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

iterator

class Reverse:
    def __init__(self, data):
        self.data = data
        self.index = len(data)

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == 0:
            raise StopIteration
        self.index = self.index - 1
        return self.data[self.index]

Возвращаясь к iterable

class ReversedList(list):
    def __iter__(self):
        return Reverse(self)

Возвращаясь к iterable

iterable = ReversedList([1, 2, 3])
for element in iterable:
    print(element)

# 3
# 2
# 1

Итого

Генераторы

Что это

Рецепт генератора

  1. Начните писать функцию
  2. Замените return на yield
  3. ????????
  4. PROFIT

Пример

def odd_printer(data):
    for index in range(len(word)):
        if index % 2 != 0:
            yield word[index]

Пример

for letter in odd_printer('питон'):
    print(letter)

# п
# т
# н

Generator expressions

numbers = (x**x for index in range(6))
list(numbers)

# [1, 4, 9, 16, 25]

Подытожим

Обо всяком

dict views

dict views

user = {'name': kazauwa, 'job': лентяй, 'password': 123}
user.keys()

# dict_keys(['name', 'job', 'password'])

dict views

user = {'name': kazauwa, 'job': лентяй, 'password': 123}
user.keys()

# dict_keys(['name', 'job', 'password'])

del(user['password'])

dict views

user = {'name': kazauwa, 'job': лентяй, 'password': 123}
user.keys()

# dict_keys(['name', 'job', 'password'])

del(user['password'])

# dict_keys(['name', 'job'])

dict views

sorted vs. sort

reversed vs. reverse