PYTHONL Telegram 4934
🐍 20 ещё более продвинутых однострочников на Python — часть 3

Если ты уже пишешь на Python профессионально, вот ещё приёмы, которые реально экономят строки и читаются на лету:

1. 🗃️ Группировка по ключу без pandas

groups = defaultdict(list); [groups[k].append(v) for k, v in data]


2. 🪄 Быстрое глубокое копирование объекта

copy = pickle.loads(pickle.dumps(obj, -1))


3. 📤 Отправка JSON через POST

r = requests.post(url, json=payload)


4. 📌 Проверка, что файл — это символическая ссылка

is_symlink = Path(p).is_symlink()


5. 🧩 Быстрое объединение нескольких словарей

merged = {**d1, **d2, **d3}


6. 🧪 Проверить, что список отсортирован

is_sorted = all(a <= b for a, b in zip(lst, lst[1:]))


7. 🔍 Найти все подстроки по регулярке

matches = re.findall(r'\d+', text)


8. 🌐 Извлечь домен из URL

domain = urlparse(url).netloc


9. 🧬 Преобразовать список строк в int

nums = list(map(int, str_list))


10. 📚 Считать CSV в список словарей

rows = list(csv.DictReader(open('file.csv')))


11. 🔄 Превратить int в побитовую строку

bits = f'{num:08b}'


12. 📤 Сохранить объект в JSON-файл

json.dump(obj, open('data.json', 'w'), indent=2)


13. 🧮 Убрать пустые строки из списка

lines = [l for l in lines if l.strip()]


14. 🧾 Распарсить query string в словарь

params = dict(parse_qsl('a=1&b=2'))


15. 🧰 Получить уникальные строки, сохранив порядок

seen = set(); uniq = [s for s in seq if not (s in seen or seen.add(s))]


16. 📈 Получить индекс максимального значения

idx = max(range(len(lst)), key=lst.__getitem__)


17. 🪛 Проверить, что список вложенный (2D)

is_nested = all(isinstance(i, list) for i in lst)


18. 🧱 Убрать все символы кроме букв и цифр

clean = re.sub(r'\W+', '', text)


19. Ограничить время выполнения кода

signal.alarm(2); try: ... except: ...


20. 📦 Получить структуру всех полей dataclass

fields = [f.name for f in dataclasses.fields(MyClass)]

📌 Часть 1
📌 Часть 2

@pythonl
👍117🔥5🤩1



tgoop.com/pythonl/4934
Create:
Last Update:

🐍 20 ещё более продвинутых однострочников на Python — часть 3

Если ты уже пишешь на Python профессионально, вот ещё приёмы, которые реально экономят строки и читаются на лету:

1. 🗃️ Группировка по ключу без pandas


groups = defaultdict(list); [groups[k].append(v) for k, v in data]


2. 🪄 Быстрое глубокое копирование объекта

copy = pickle.loads(pickle.dumps(obj, -1))


3. 📤 Отправка JSON через POST

r = requests.post(url, json=payload)


4. 📌 Проверка, что файл — это символическая ссылка

is_symlink = Path(p).is_symlink()


5. 🧩 Быстрое объединение нескольких словарей

merged = {**d1, **d2, **d3}


6. 🧪 Проверить, что список отсортирован

is_sorted = all(a <= b for a, b in zip(lst, lst[1:]))


7. 🔍 Найти все подстроки по регулярке

matches = re.findall(r'\d+', text)


8. 🌐 Извлечь домен из URL

domain = urlparse(url).netloc


9. 🧬 Преобразовать список строк в int

nums = list(map(int, str_list))


10. 📚 Считать CSV в список словарей

rows = list(csv.DictReader(open('file.csv')))


11. 🔄 Превратить int в побитовую строку

bits = f'{num:08b}'


12. 📤 Сохранить объект в JSON-файл

json.dump(obj, open('data.json', 'w'), indent=2)


13. 🧮 Убрать пустые строки из списка

lines = [l for l in lines if l.strip()]


14. 🧾 Распарсить query string в словарь

params = dict(parse_qsl('a=1&b=2'))


15. 🧰 Получить уникальные строки, сохранив порядок

seen = set(); uniq = [s for s in seq if not (s in seen or seen.add(s))]


16. 📈 Получить индекс максимального значения

idx = max(range(len(lst)), key=lst.__getitem__)


17. 🪛 Проверить, что список вложенный (2D)

is_nested = all(isinstance(i, list) for i in lst)


18. 🧱 Убрать все символы кроме букв и цифр

clean = re.sub(r'\W+', '', text)


19. Ограничить время выполнения кода

signal.alarm(2); try: ... except: ...


20. 📦 Получить структуру всех полей dataclass

fields = [f.name for f in dataclasses.fields(MyClass)]

📌 Часть 1
📌 Часть 2

@pythonl

BY Python/ django


Share with your friend now:
tgoop.com/pythonl/4934

View MORE
Open in Telegram


Telegram News

Date: |

Deputy District Judge Peter Hui sentenced computer technician Ng Man-ho on Thursday, a month after the 27-year-old, who ran a Telegram group called SUCK Channel, was found guilty of seven charges of conspiring to incite others to commit illegal acts during the 2019 extradition bill protests and subsequent months. Just as the Bitcoin turmoil continues, crypto traders have taken to Telegram to voice their feelings. Crypto investors can reduce their anxiety about losses by joining the “Bear Market Screaming Therapy Group” on Telegram. Private channels are only accessible to subscribers and don’t appear in public searches. To join a private channel, you need to receive a link from the owner (administrator). A private channel is an excellent solution for companies and teams. You can also use this type of channel to write down personal notes, reflections, etc. By the way, you can make your private channel public at any moment. End-to-end encryption is an important feature in messaging, as it's the first step in protecting users from surveillance. Telegram offers a powerful toolset that allows businesses to create and manage channels, groups, and bots to broadcast messages, engage in conversations, and offer reliable customer support via bots.
from us


Telegram Python/ django
FROM American