
Python 以其简洁性和强大的功能成为开发者最喜爱的编程语言之一。本文将介绍40个Python常见场景的代码示例,涵盖基础语法、数据处理、文件操作、网络编程等多个方面。
用途:通过递归示范函数自调用思想。
def factorial(n: int) ->int:
return1 if n == 0elsen*factorial(n-1)
print(factorial(5))120用途:展示多重赋值与循环的高效写法。
def fibonacci(n: int) ->list[int]:
a, b, seq = 0, 1, []
for_in range(n):
seq.append(a)
a, b = b, a+b
return seq
print(fibonacci(10))[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]用途:演示数学运算 + 早停优化的算法思维。
import math
def is_prime(n: int) ->bool:
if n<= 1:
return False
for i in range(2, int(math.isqrt(n)) +1):
if n%i == 0:
return False
return True
print(is_prime(17), is_prime(20))True False用途:用切片完成一行代码反转。
text = "Hello, World!"
print(text[::-1])!dlroW ,olleH用途:借助 Counter 快速完成词频统计。
from collections import Counter
text = "hello world hello python world"
freq = Counter(text.split())
print(freq)Counter({'hello': 2, 'world': 2, 'python': 1})用途:演示文件 I/O + JSON 解析组合。
import json, tempfile, os
with tempfile.NamedTemporaryFile(mode="w+", delete=False) asf:
json.dump({"name": "Alice", "age": 25}, f)
f.flush()
with open(f.name) as rf:
data = json.load(rf)
os.unlink(f.name)
print(data){'name': 'Alice', 'age': 25}用途:用 csv.writer 实现结构化数据落盘。
import csv, tempfile, os
rows = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with tempfile.NamedTemporaryFile(mode="w+", delete=False, newline="") asf:
writer = csv.writer(f)
writer.writerows(rows)
f.flush()
with open(f.name) as rf:
print(rf.read().strip())
os.unlink(f.name)Name,Age
Alice,25
Bob,30用途:用 requests抓取 REST API 数据。
import requests
resp = requests.get("https://httpbin.org/json")
print(resp.status_code, resp.json()["slideshow"]["title"])200 Five reasons to move to DX-Math用途:一行命令共享当前目录。
# 终端执行:python -m http.server 8000
# 浏览器访问 http://localhost:8000用途:利用 ThreadPoolExecutor并行下载提升速度。
import concurrent.futures, requests, tempfile, os
urls = ["https://httpbin.org/bytes/100", "https://httpbin.org/bytes/200"]
def fetch(url, idx):
returnidx, requests.get(url).content
with tempfile.TemporaryDirectory() astmp:
with concurrent.futures.ThreadPoolExecutor() aspool:
for idx, datainpool.map(fetch, urls, range(len(urls))):
path = os.path.join(tmp, f"file{idx}")
withopen(path, "wb") asf:
f.write(data)
print(f"file{idx} downloaded, {len(data)} bytes")file0 downloaded, 100 bytes
file1 downloaded, 200 bytes用途:无侵入式性能测量。
import time, functools
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
t0 = time.perf_counter()
res = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter()-t0:.4f}s")
return res
return wrapper
@timer
def demo():
time.sleep(0.5)
demo()demo took 0.5003s用途:逐行流式处理,节省内存。
import tempfile, os
with tempfile.NamedTemporaryFile(mode="w+", delete=False) asf:
f.write("line1\nline2\nline3")
f.flush()
def read_large(path):
with open(path) as fh:
for lineinfh:
yield line.strip()
for ln in read_large(f.name):
print(ln)
os.unlink(f.name)line1
line2
line3用途:确保资源正确释放(如锁、连接)。
class DB:
def__enter__(self):
print("Connecting")
returnself
def__exit__(self, *exc):
print("Disconnecting")
with DB() as db:
print("Querying...")Connecting
Querying...
Disconnecting用途:可读性强的字符串插值。
name, age = "Alice", 25
print(f"My name is {name} and I am {age} years old.")My name is Alice and I am 25 years old.用途:类型安全的常量集合。
from enum import Enum, auto
class Color(Enum):
RED = auto()
GREEN = auto()
print(Color.RED)Color.RED@dataclass 精简类 用途:自动实现__init__/__repr__ 等魔法方法。
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int = 0
p = Person("Bob", 30)
print(p)Person(name='Bob', age=30)用途:zip 让多列表同步循环优雅简洁。
names = ["Alice", "Bob"]
ages = [25, 30]
for n, a in zip(names, ages):
print(f"{n} is {a}")Alice is 25
Bob is 30map 批量转换 用途:函数式地对序列元素应用操作。
nums = [1, 2, 3, 4]
print(list(map(str, nums)))['1', '2', '3', '4']filter 条件筛选 用途:一行代码完成布尔过滤。
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambdax: x%2 == 0, nums))
print(evens)[2, 4]reduce 累积计算 用途:把序列压缩成单一值。
from functools import reduce
product = reduce(lambdax, y: x*y, [1, 2, 3, 4, 5])
print(product)120namedtuple 轻量对象 用途:只读记录,字段名访问。
from collections impor tnamedtuple
Point = namedtuple("Point", "x y")
p = Point(3, 4)
print(p.x, p.y)3 4defaultdict 优雅计数 用途:自动初始化缺失键值。
from collections import defaultdict
cnt = defaultdict(int)
for w in ["a", "b", "a"]:
cnt[w] += 1
print(cnt)defaultdict(<class 'int'>, {'a': 2, 'b': 1})OrderedDict 保序字典 用途:保持插入顺序。
from collections import OrderedDict
od = OrderedDict([("first", 1), ("second", 2)])
print(list(od))['first', 'second']ChainMap 链式字典 用途:多 dict 只读视图,查找链式回退。
from collections import ChainMap
a = {"x": 1}
b = {"x": 9, "y": 2}
cm = ChainMap(a, b)
print(cm["x"], cm["y"])1 2deque 高效双端队列 用途:O(1) 头尾增删,旋转操作。
from collections import deque
dq = deque([1, 2])
dq.appendleft(0)
dq.append(3)
print(dq.popleft(), dq.pop())0 3heapq 优先队列 用途:最小堆实现任务调度、Top-K。
import heapq
tasks = []
heapq.heappush(tasks, (2, "write"))
heapq.heappush(tasks, (1, "eat"))
print(heapq.heappop(tasks))(1, 'eat')bisect 二分查找 用途:在已排序序列中快速定位插入点。
import bisect
lst = [1, 3, 3, 7]
print(bisect.bisect_left(lst, 3), bisect.bisect_right(lst, 3))1 3itertools 排列组合 用途:惰性生成排列/组合,避免内存爆炸。
import itertools as it
print(list(it.permutations("AB", 2)))
print(list(it.combinations("ABC", 2)))[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C')]
[('A', 'B'), ('A', 'C'), ('B', 'C')]partial 偏函数 用途:预设部分参数,生成新函数。
from functools import partial
def power(base, exp):
returnbase**exp
square = partial(power, exp=2)
print(square(5))25operator 函数式工具 用途:用函数形式替代 lambda,提升可读性。
from operator import itemgetter
rows = [("a", 3), ("b", 1)]
print(sorted(rows, key=itemgetter(1)))[('b', 1), ('a', 3)]@contextmanager 简化上下文 用途:一行装饰器把生成器变成上下文管理器。
from contextlib import contextmanager
@contextmanager
def managed():
print("enter")
yield
print("exit")
with managed():
print("work")enter
work
exitpathlib 面向对象路径 用途:链式路径拼接与跨平台文件系统操作。
from pathlib import Path
p = Path("/tmp") /"demo"/"file.txt"
print(p.parent) # /tmp/demo
print(p.suffix) # .txtglob 模式匹配文件 用途:通配符批量查找文件。
import glob, tempfile, os
with tempfile.TemporaryDirectory() as td:
Path(td, "a.py").touch()
print(glob.glob(f"{td}/*.py"))['/tmp/.../a.py']shutil 高级文件操作 用途:复制、移动、删除整棵树。
import tempfile, shutil, os
with tempfile.TemporaryDirectory() as td:
src = os.path.join(td, "src.txt")
dst = os.path.join(td, "dst.txt")
open(src, "w").write("hi")
shutil.copy(src, dst)
print(os.listdir(td))['src.txt', 'dst.txt']tempfile 安全临时文件 用途:自动清理的临时文件/目录。
import tempfile
with tempfile.NamedTemporaryFile(mode="w+", delete=False) as f:
f.write("temp")
print(f.name)/tmp/tmp34xyzabsubprocess 运行外部命令 用途:捕获输出,与系统命令交互。
import subprocess
result = subprocess.run(["echo", "hello"], capture_output=True, text=True)
print(result.stdout.strip())hellologging 分级日志 用途:结构化记录程序运行轨迹。
import logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logging.info("App started")
logging.warning("Check config")INFO: App started
WARNING: Check configunittest 单元测试 用途:内置框架保障代码质量。
import unittest
def add(a, b): returna+b
class TestMath(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5)
if__name__ == "__main__":
unittest.main(argv=[""], exit=False).
----------------------------------------------------------------------
Ran 1 test in 0.000spytest 简洁测试 用途:零样板的流行第三方测试框架。
# 保存为 test_demo.py
def add(a, b): returna+b
def test_add():
assertadd(2, 3) == 5运行 pytest -q:
.
1 passed in 0.01sasyncio 异步并发 用途:单线程并发 I/O,提升吞吐量。
import asyncio
async def greet():
print("Hello")
awaitasyncio.sleep(0.5)
print("World")
asyncio.run(greet())Hello
Worldasyncio模块提供了编写异步代码的基础设施。
这些示例涵盖了Python编程中的常见场景,从基础语法到高级特性,希望能帮助更好地掌握Python编程。
“无他,惟手熟尔”!有需要的用起来。
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!😊
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!