BOOKPYTHON Telegram 3246
Шпаргалка по Python. Часть 1

1. Основы работы с коллекциями

#### Списки (List) и генераторы списков:
- Быстрая инициализация списка:

lst = [x**2 for x in range(10) if x % 2 == 0]


- Использование map и filter:

squares = list(map(lambda x: x**2, range(10)))
evens = list(filter(lambda x: x % 2 == 0, range(10)))


- Развертывание списка (spreading):

lst1 = [1, 2, 3]
lst2 = [4, 5]
combined = [*lst1, *lst2]


#### Словари (Dict):
- Генерация словаря:

dct = {x: x**2 for x in range(5)}


- Объединение двух словарей:

dct1 = {'a': 1, 'b': 2}
dct2 = {'b': 3, 'c': 4}
merged = {**dct1, **dct2} # {'a': 1, 'b': 3, 'c': 4}


#### Множества (Set):
- Операции с множествами:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2 # Объединение
intersection = set1 & set2 # Пересечение


2. Работа с файлами

#### Чтение и запись:

with open('file.txt', 'r') as f:
content = f.read()

with open('file.txt', 'w') as f:
f.write("Hello, World!")


#### Управление JSON:

import json

data = {'key': 'value'}
with open('data.json', 'w') as f:
json.dump(data, f)

with open('data.json', 'r') as f:
data = json.load(f)


3. Декораторы

#### Простой декоратор:

def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()


#### Декоратор с аргументами:

def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator

@repeat(3)
def say_hello():
print("Hello!")

say_hello()


4. Итераторы и генераторы

#### Создание итератора:

class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.current >= self.end:
raise StopIteration
self.current += 1
return self.current - 1

for num in MyIterator(1, 5):
print(num)


#### Генераторы:

def my_generator():
for i in range(3):
yield i

for value in my_generator():
print(value)


#### Генераторы с обработкой состояния:

def countdown(n):
while n > 0:
yield n
n -= 1


5. Менеджеры контекста

#### Создание собственного менеджера контекста:

class MyContextManager:
def __enter__(self):
print("Entering context")
return self

def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting context")

with MyContextManager():
print("Inside context")


#### Менеджеры контекста с contextlib:

from contextlib import contextmanager

@contextmanager
def my_context():
print("Entering")
yield
print("Exiting")

with my_context():
print("Inside")


6. Асинхронное программирование

#### Асинхронные функции и await:

import asyncio

async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")

asyncio.run(say_hello())


#### Запуск нескольких задач одновременно:

async def task1():
await asyncio.sleep(1)
print("Task 1 done")

async def task2():
await asyncio.sleep(2)
print("Task 2 done")

async def main():
await asyncio.gather(task1(), task2())

asyncio.run(main())


👉@BookPython
👍7🎉2



tgoop.com/BookPython/3246
Create:
Last Update:

Шпаргалка по Python. Часть 1

1. Основы работы с коллекциями

#### Списки (List) и генераторы списков:
- Быстрая инициализация списка:


lst = [x**2 for x in range(10) if x % 2 == 0]


- Использование map и filter:

squares = list(map(lambda x: x**2, range(10)))
evens = list(filter(lambda x: x % 2 == 0, range(10)))


- Развертывание списка (spreading):

lst1 = [1, 2, 3]
lst2 = [4, 5]
combined = [*lst1, *lst2]


#### Словари (Dict):
- Генерация словаря:

dct = {x: x**2 for x in range(5)}


- Объединение двух словарей:

dct1 = {'a': 1, 'b': 2}
dct2 = {'b': 3, 'c': 4}
merged = {**dct1, **dct2} # {'a': 1, 'b': 3, 'c': 4}


#### Множества (Set):
- Операции с множествами:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2 # Объединение
intersection = set1 & set2 # Пересечение


2. Работа с файлами

#### Чтение и запись:

with open('file.txt', 'r') as f:
content = f.read()

with open('file.txt', 'w') as f:
f.write("Hello, World!")


#### Управление JSON:

import json

data = {'key': 'value'}
with open('data.json', 'w') as f:
json.dump(data, f)

with open('data.json', 'r') as f:
data = json.load(f)


3. Декораторы

#### Простой декоратор:

def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper

@my_decorator
def say_hello():
print("Hello!")

say_hello()


#### Декоратор с аргументами:

def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator

@repeat(3)
def say_hello():
print("Hello!")

say_hello()


4. Итераторы и генераторы

#### Создание итератора:

class MyIterator:
def __init__(self, start, end):
self.current = start
self.end = end

def __iter__(self):
return self

def __next__(self):
if self.current >= self.end:
raise StopIteration
self.current += 1
return self.current - 1

for num in MyIterator(1, 5):
print(num)


#### Генераторы:

def my_generator():
for i in range(3):
yield i

for value in my_generator():
print(value)


#### Генераторы с обработкой состояния:

def countdown(n):
while n > 0:
yield n
n -= 1


5. Менеджеры контекста

#### Создание собственного менеджера контекста:

class MyContextManager:
def __enter__(self):
print("Entering context")
return self

def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting context")

with MyContextManager():
print("Inside context")


#### Менеджеры контекста с contextlib:

from contextlib import contextmanager

@contextmanager
def my_context():
print("Entering")
yield
print("Exiting")

with my_context():
print("Inside")


6. Асинхронное программирование

#### Асинхронные функции и await:

import asyncio

async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")

asyncio.run(say_hello())


#### Запуск нескольких задач одновременно:

async def task1():
await asyncio.sleep(1)
print("Task 1 done")

async def task2():
await asyncio.sleep(2)
print("Task 2 done")

async def main():
await asyncio.gather(task1(), task2())

asyncio.run(main())


👉@BookPython

BY Библиотека Python разработчика | Книги по питону


Share with your friend now:
tgoop.com/BookPython/3246

View MORE
Open in Telegram


Telegram News

Date: |

“Hey degen, are you stressed? Just let it all out,” he wrote, along with a link to join the group. fire bomb molotov November 18 Dylan Hollingsworth yau ma tei The group also hosted discussions on committing arson, Judge Hui said, including setting roadblocks on fire, hurling petrol bombs at police stations and teaching people to make such weapons. The conversation linked to arson went on for two to three months, Hui said. In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist. "Doxxing content is forbidden on Telegram and our moderators routinely remove such content from around the world," said a spokesman for the messaging app, Remi Vaughn.
from us


Telegram Библиотека Python разработчика | Книги по питону
FROM American