
1. 列表/字典推导式多层筛选+条件判断(数据处理必用)
嵌套推导,同时完成过滤、运算、分支赋值,数据分析高频
# 数据源:学生成绩列表students = [ {”name”: ”张三”, ”score”: 88, ”class”: 1}, {”name”: ”李四”, ”score”: 59, ”class”: 1}, {”name”: ”王五”, ”score”: 95, ”class”: 2}, {”name”: ”赵六”, ”score”: 45, ”class”: 2}]# 筛选一班及格学生,分数分级标注result = [ { ”username”: item[”name”], ”level”: ”优秀” if item[”score”] >= 85 else ”及格” } for item in students if item[”class”] == 1anditem[”score”] >= 60]print(result)
2. with上下文管理器批量读写大文件(自动分片,避免内存溢出)
处理日志、超大文本工业标准写法,逐行读取不一次性加载全部内容
def read_large_file(file_path, encoding=”utf-8”): line_list = [] with open(file_path, ”r”, encoding=encoding) as f:# 逐行迭代,低内存占用 for line in f: strip_line = line.strip() if strip_line: line_list.append(strip_line) return line_listdef write_batch_file(file_path, data_list): with open(file_path, ”a”, encoding=”utf-8”) as f: f.writelines([line + ”\n” for line in data_list])# 调用text_data = read_large_file(”log.txt”)write_batch_file(”output.txt”, text_data[:10])
3. 完整异常捕获(多层异常+finally+自定义报错信息)
项目开发标准容错模板,区分多种异常,统一资源收尾
def safe_divide(a, b): try: num_a = float(a) num_b = float(b) res = num_a / num_b except ValueError as e: print(f”参数类型错误:{str(e)}”) return None except ZeroDivisionError: print(”除数不能为0”) return None except Exception as err: print(f”未知异常:{err}”) return None finally: print(”计算流程执行结束,清理临时资源”) return resprint(safe_divide(”100”, ”0”))print(safe_divide(”200”, ”4”))
4. 递归函数+缓存装饰器实现高效斐波那契(装饰器进阶用法)
lru_cache缓存重复计算,大幅优化递归性能,算法面试高频
from functools import lru_cache@lru_cache(maxsize=1024)def fib(n: int) -> int: if n <= 1: return n return fib(n - 1) + fib(n - 2)# 批量输出前20项fib_list = [fib(i) for i in range(20)]print(fib_list)
5. requests爬虫完整模板(请求头、超时、状态码判断、编码处理)
日常爬取网页通用代码,规避基础反爬,健壮性拉满
import requestsdef get_html(url: str, timeout=10): headers = { ”User-Agent”: ”Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36” } try: resp = requests.get(url, headers=headers, timeout=timeout) resp.raise_for_status()# 状态码非200直接抛出异常 resp.encoding = resp.apparent_encoding return resp.text except requests.exceptions.RequestException as e: print(f”网页请求失败:{e}”) return Nonehtml = get_html(”https://www.baidu.com”)print(html[:300])
6. 字典分组聚合(itertools.groupby批量数据归类统计)
无需循环嵌套,快速对列表数据分组统计,数据分析刚需
from itertools import groupbysales_data = [ {”region”: ”华东”, ”money”: 1200}, {”region”: ”华东”, ”money”: 800}, {”region”: ”华北”, ”money”: 1500}, {”region”: ”华北”, ”money”: 600}]# 先按区域排序,groupby要求数据连续sales_data.sort(key=lambda x: x[”region”])group_result = {}for area, group in groupby(sales_data, key=lambda x: x[”region”]): total = sum(item[”money”] for item in group) group_result[area] = totalprint(group_result)
7. 多线程并发任务(threading+锁,解决多线程资源竞争)
IO密集场景并发加速,加锁防止数据错乱,爬虫/批量处理常用
import threadingimport timecount = 0lock = threading.Lock()def add_task(loop_times): global count for _ in range(loop_times): lock.acquire() try: count += 1 finally: lock.release() time.sleep(0.001)thread1 = threading.Thread(target=add_task, args=(1000,))thread2 = threading.Thread(target=add_task, args=(1000,))thread1.start()thread2.start()thread1.join()thread2.join()print(”最终计数:”, count)
8. 时间格式化工具函数(时间戳、字符串、datetime互相转换)
后端、日志处理高频工具,封装一套通用转换逻辑
from datetime import datetimeimport time# 时间戳转格式化字符串def ts_to_str(timestamp=None, fmt=”%Y-%m-%d %H:%M:%S”): if timestamp is None: timestamp = time.time() return datetime.fromtimestamp(timestamp).strftime(fmt)# 字符串转时间戳def str_to_ts(time_str, fmt=”%Y-%m-%d %H:%M:%S”): dt = datetime.strptime(time_str, fmt) return dt.timestamp()now_str = ts_to_str()now_ts = str_to_ts(now_str)print(”当前时间字符串:”, now_str)print(”对应时间戳:”, now_ts)
9. 类封装工具库(私有属性、实例方法、静态方法综合运用)
面向对象标准写法,项目工具类通用模板
class StringTool:# 私有属性 __version = ”1.0.0” def __init__(self, raw_str): self.raw = raw_str.strip()# 实例方法 def reverse_str(self): return self.raw[::-1]# 静态方法,无需实例化调用 @staticmethod def remove_duplicate(lst): return list(set(lst))tool = StringTool(”hello python”)print(tool.reverse_str())print(StringTool.remove_duplicate([1,2,2,3]))
10. json文件读写工具(序列化、格式化存储、读取自动解析)
配置文件、接口数据持久化最常用方案
import jsondef save_json(file_path, data, indent=2): with open(file_path, ”w”, encoding=”utf-8”) as f: json.dump(data, f, ensure_ascii=False, indent=indent)def load_json(file_path): with open(file_path, ”r”, encoding=”utf-8”) as f: return json.load(f)# 测试数据info = {”project”: ”python_demo”, ”author”: ”研究生”, ”nums”: [11,22,33]}save_json(”config.json”, info)load_data = load_json(”config.json”)print(load_data[”project”])
这是算是python在一些领域的稍微复杂的用法,不过,代码难度还是非常低的,只要你有python代码基础。学会这些代码,能丰富你的知识库,这样,在你面对一些类似问题时,能够想到具体要用什么样的代码!