Словарь операций
Функции хранятся в словаре и выбираются по строковому ключу.
def add(x, y):
return x + y
def multiply(x, y):
return x * y
operations = {"+": add, "*": multiply}
print(operations["+"](10, 5))
print(operations["*"](10, 5))map и filter
map меняет форму данных, filter оставляет только нужные элементы.
numbers = [5, 3, 4, 1, 5, 2]
squares = list(map(lambda x: x ** 2, numbers))
odd_numbers = list(filter(lambda x: x % 2 == 1, numbers))
print(squares)
print(odd_numbers)Сортировка с key
key возвращает значение, по которому Python сравнивает элементы.
people = [("Alice", 25), ("Bob", 20), ("Charlie", 23)]
print(sorted(people, key=lambda person: person[1]))
print(max(people, key=lambda person: person[1]))