惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
GbyAI
GbyAI
G
Google Developers Blog
Engineering at Meta
Engineering at Meta
月光博客
月光博客
腾讯CDC
Recent Announcements
Recent Announcements
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
阮一峰的网络日志
阮一峰的网络日志
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
Last Week in AI
Last Week in AI
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
aimingoo的专栏
aimingoo的专栏
Google DeepMind News
Google DeepMind News
Y
Y Combinator Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Martin Fowler
Martin Fowler
A
About on SuperTechFans
博客园 - 叶小钗

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
50 Python One-Liners Every Developer Should Have in Their...
PyToolKit · 2026-06-03 · via DEV Community
Cover image for 50 Python One-Liners Every Developer Should Have in Their Toolbox

PyToolKit

LOGOPython's expressiveness lets you do in a single line what takes five in other languages. Here are 50 battle-tested one-liners I've collected over years of writing automation scripts.

File & System

lines = open('data.txt').read().splitlines()
open('out.txt', 'w').write('\n'.join(my_list))
py_files = [str(p) for p in __import__('pathlib').Path('.').rglob('*.py')]
__import__('os').makedirs('output/reports', exist_ok=True)
all_files = [f for r, _, fs in __import__('os').walk('.') for f in fs]
latest = max(__import__('pathlib').Path('.').glob('*'), key=lambda p: p.stat().st_mtime)

Data Structures

flat = [item for sublist in nested for item in sublist]
unique = list(dict.fromkeys(my_list))
most_common = max(set(my_list), key=my_list.count)
transposed = list(zip(*matrix))
merged = dict1 | dict2
inverted = {v: k for k, v in original.items()}
d = dict(zip(keys, values))
filtered = {k: v for k, v in d.items() if v > threshold}

String Manipulation

reversed_str = s[::-1]
is_pal = lambda s: s == s[::-1]
freq = {c: s.count(c) for c in set(s)}
formatted = f"{1234567:,}"
slug = '-'.join(re.sub(r'[^\w\s-]', '', text.lower()).split())
nums = [int(x) for x in re.findall(r'\d+', text)]
titled = ' '.join(w[0].upper() + w[1:] for w in s.split())
no_ws = ''.join(s.split())
trunc = lambda s, n: s[:n-3] + '...' if len(s) > n else s

Functional & List Comprehensions

evens = [x for x in nums if x % 2 == 0]
squared = [x**2 for x in nums]
result = [x*2 for x in nums if x > 0]
common = list(set(a) & set(b))
diff = list(set(a) - set(b))
chunks = [lst[i:i+n] for i in range(0, len(lst), n)]
float_range = lambda start, stop, step: [start + i*step for i in range(int((stop-start)/step))]

Date, Time & Math

today = __import__('datetime').date.today().isoformat()
days = (lambda d1, d2: (d2-d1).days)(__import__('datetime').date(2026, 1, 1), __import__('datetime').date.today())
dates = [__import__('datetime').date.today() + __import__('datetime').timedelta(days=i) for i in range(30)]
fact = lambda n: __import__('math').prod(range(1, n + 1))
is_prime = lambda n: n > 1 and all(n % i for i in range(2, int(n**0.5) + 1))
human = lambda b: f"{b/1<<30:.1f} GB" if b >= 1<<30 else (f"{b/1<<20:.1f} MB" if b >= 1<<20 else f"{b/1024:.1f} KB")

Web, JSON & APIs

data = __import__('json').loads(__import__('urllib.request').urlopen('https://api.example.com/data').read())
print(__import__('json').dumps(data, indent=2, ensure_ascii=False))
__import__('urllib.request').urlretrieve('https://example.com/file.pdf', 'local.pdf')
params = dict(__import__('urllib.parse').parse_qsl(__import__('urllib.parse').urlparse(url).query))
qs = __import__('urllib.parse').urlencode({'key': 'val', 'page': 1})
domain = __import__('urllib.parse').urlparse(url).hostname

Regex & Text

emails = __import__('re').findall(r'[\w.+-]+@[\w-]+\.[\w.-]+', text)
is_email = bool(__import__('re').match(r'^[\w.+-]+@[\w-]+\.[\w.-]+$', email))
clean = __import__('re').sub(r'\s+', ' ', text).strip()
parts = __import__('re').split(r'[;|,]', 'a;b|c,d')
between = __import__('re').findall(r'<tag>(.*?)</tag>', html)
plain = __import__('re').sub(r'<[^>]+>', '', html)


These are great for quick tasks, but if you script often you'll eventually want reusable versions with error handling and a proper CLI.

That's why I built PyToolkit — all these patterns plus dozens more, organized into 5 modules (files, data, PDFs, web, images) with a unified command-line interface.

https://toolkitpy.com — $5 one-time, lifetime access.

Happy coding!