Python3 实例
Ten small programs that show up in real work: parsing, dedupe, retry, pagination, batching.
Key PointsThese are patterns, not puzzles — each one solves a task you will meet in a real backend job.
1. Parse a CSV Report
Python
import csv
from collections import defaultdict
revenue = defaultdict(float)
with open("orders.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
revenue[row["city"]] += float(row["amount"])
for city, total in sorted(revenue.items(), key=lambda kv: -kv[1])[:5]:
print(f"{city}: {total:,.2f}")2. Dedupe While Keeping Order
Python
items = ["b", "a", "b", "c", "a"]
unique = list(dict.fromkeys(items)) # ['b', 'a', 'c']3. Retry with Backoff
Python
import time
def retry(func, attempts=3, base=0.5):
for i in range(attempts):
try:
return func()
except (TimeoutError, ConnectionError):
if i == attempts - 1:
raise
time.sleep(base * 2 ** i)4. Group by Key
Python
from itertools import groupby
rows = [{"city": "bj", "n": 1}, {"city": "sh", "n": 2}, {"city": "bj", "n": 3}]
rows.sort(key=lambda r: r["city"]) # groupby 要求先排序
for city, group in groupby(rows, key=lambda r: r["city"]):
print(city, sum(r["n"] for r in group))5. Chunk a List
Python
def chunks(seq, size):
for i in range(0, len(seq), size):
yield seq[i:i + size]
for batch in chunks(list(range(10)), 3):
print(batch) # [0,1,2] [3,4,5] [6,7,8] [9]6. Flatten Nested Data
Python
def flatten(items):
for x in items:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]7. Safe Integer Parsing
Python
def to_int(value, default=0):
try:
return int(str(value).strip())
except (TypeError, ValueError):
return default
print(to_int(" 42 "), to_int("abc"), to_int(None)) # 42 0 08. Count Word Frequency
Python
import re
from collections import Counter
text = "the quick brown fox jumps over the lazy dog the end"
words = re.findall(r"[a-z']+", text.lower())
print(Counter(words).most_common(3))
# [('the', 3), ('quick', 1), ('brown', 1)]9. Format Bytes and Durations
Python
def human_bytes(n):
for unit in ("B", "KB", "MB", "GB", "TB"):
if n < 1024:
return f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} PB"
def human_duration(seconds):
m, s = divmod(int(seconds), 60)
h, m = divmod(m, 60)
return f"{h}h{m:02d}m{s:02d}s"
print(human_bytes(1536), human_duration(3725)) # 1.5 KB 1h02m05s10. Simple Timer Decorator
Python
import functools
import time
def timed(func):
@functools.wraps(func)
def wrapper(*a, **kw):
t0 = time.perf_counter()
try:
return func(*a, **kw)
finally:
print(f"{func.__name__}: {(time.perf_counter() - t0) * 1000:.1f} ms")
return wrapperRun these snippets with
python3 -c or a scratch file before wiring them into a project — every one of them is easy to adapt but hard to debug blind.1. 解析 CSV 报表
Python
import csv
from collections import defaultdict
revenue = defaultdict(float)
with open("orders.csv", encoding="utf-8", newline="") as f:
for row in csv.DictReader(f):
revenue[row["city"]] += float(row["amount"])
for city, total in sorted(revenue.items(), key=lambda kv: -kv[1])[:5]:
print(f"{city}: {total:,.2f}")2. 保序去重
Python
items = ["b", "a", "b", "c", "a"]
unique = list(dict.fromkeys(items)) # ['b', 'a', 'c']3. 带退避的重试
Python
import time
def retry(func, attempts=3, base=0.5):
for i in range(attempts):
try:
return func()
except (TimeoutError, ConnectionError):
if i == attempts - 1:
raise
time.sleep(base * 2 ** i)4. 按 key 分组
Python
from itertools import groupby
rows = [{"city": "bj", "n": 1}, {"city": "sh", "n": 2}, {"city": "bj", "n": 3}]
rows.sort(key=lambda r: r["city"]) # groupby 要求先排序
for city, group in groupby(rows, key=lambda r: r["city"]):
print(city, sum(r["n"] for r in group))5. 分批处理
Python
def chunks(seq, size):
for i in range(0, len(seq), size):
yield seq[i:i + size]
for batch in chunks(list(range(10)), 3):
print(batch) # [0,1,2] [3,4,5] [6,7,8] [9]6. 打平嵌套结构
Python
def flatten(items):
for x in items:
if isinstance(x, list):
yield from flatten(x)
else:
yield x
print(list(flatten([1, [2, [3, 4]], 5]))) # [1, 2, 3, 4, 5]7. 安全转整数
Python
def to_int(value, default=0):
try:
return int(str(value).strip())
except (TypeError, ValueError):
return default
print(to_int(" 42 "), to_int("abc"), to_int(None)) # 42 0 08. 词频统计
Python
import re
from collections import Counter
text = "the quick brown fox jumps over the lazy dog the end"
words = re.findall(r"[a-z']+", text.lower())
print(Counter(words).most_common(3))
# [('the', 3), ('quick', 1), ('brown', 1)]9. 格式化容量与时长
Python
def human_bytes(n):
for unit in ("B", "KB", "MB", "GB", "TB"):
if n < 1024:
return f"{n:.1f} {unit}"
n /= 1024
return f"{n:.1f} PB"
def human_duration(seconds):
m, s = divmod(int(seconds), 60)
h, m = divmod(m, 60)
return f"{h}h{m:02d}m{s:02d}s"
print(human_bytes(1536), human_duration(3725)) # 1.5 KB 1h02m05s10. 计时装饰器
Python
import functools
import time
def timed(func):
@functools.wraps(func)
def wrapper(*a, **kw):
t0 = time.perf_counter()
try:
return func(*a, **kw)
finally:
print(f"{func.__name__}: {(time.perf_counter() - t0) * 1000:.1f} ms")
return wrapper先把片段用
python3 -c 或临时文件跑通再接入项目 —— 这些代码好改但不好盲调。