当你刚开始学习 Python 时,让代码正确运行是你的首要任务。但随着你编程经验的提升,你会希望自己的代码不仅能正确执行,还能更加高效。
高效的代码运行速度更快、占用更少的内存,在处理大型数据集时也能更好地扩展。好消息是,你不需要多年的经验,也能开始写出高效的 Python 代码。只需掌握几个简单技巧,即使是初学者也能让代码变得更高效。
本文将带你掌握让 Python 代码更高效的实用技巧。每种技巧都会提供清晰的对比,展示不够高效的写法和更高效的替代方案。
你可以在 GitHub 上找到完整代码
https://github.com/balapriyac/python-basics/tree/main/efficient-python-for-beginners
1. 使用内置函数替代手动实现
Python 提供了许多内置函数,能高效地完成各种常见操作。这些函数经过优化,能够以最高效的方式处理常见任务。
不推荐的写法:
def process_sales_data(sales):
highest_sale = sales[0]
for sale in sales:
if sale > highest_sale:
highest_sale = sale
total_sales = 0
for sale in sales:
total_sales += sale
return highest_sale, total_sales, total_sales / len(sales)
这种写法需要遍历列表两次,分别查找最高销售额和总销售额,效率较低。
推荐写法:
def process_sales_data(sales):
return max(sales), sum(sales), sum(sales) / len(sales)
利用 Python 内置的max()和sum()函数,不仅速度更快,代码更简洁,也更不易出错。
小贴士:当你为集合数据编写循环以实现常见操作时,先看看是否有内置函数可以更高效地完成。
2. 使用列表推导式,但注意可读性
列表推导式是根据已有列表或序列生成新列表的利器。它们比等效的 for 循环更简洁,通常也更快。
不推荐的写法:
def get_premium_customer_emails(customers):
premium_emails = []
for customer in customers:
if customer['membership_level'] == 'premium' and customer['active']:
email = customer['email'].lower().strip()
premium_emails.append(email)
return premium_emails
这种方式每次循环都调用.append(),存在一定的开销。
推荐写法:
def get_premium_customer_emails(customers):
return [
customer['email'].lower().strip()
for customer in customers
if customer['membership_level'] == 'premium' and customer['active']
]
列表推导式将整个操作浓缩为一行,既高效又易于理解(熟悉这种写法后)。
注意:列表推导式适合处理逻辑简单的情况。如果转换逻辑过于复杂,建议分步处理或回归传统循环以提升可读性。
3. 使用集合和字典实现快速查找
当你需要判断一个元素是否存在于集合中或频繁查找数据时,集合(set)和字典(dict)的效率远高于列表。无论集合大小如何,它们都能实现近乎常数时间的查找,而列表查找的效率会随着列表增长而降低。
不推荐的写法:
def has_permission(user_id, permitted_users):
# permitted_users 是用户ID列表
for p_user in permitted_users:
if p_user == user_id:
return True
return False
permitted_users = [1001, 1023, 1052, 1076, 1088, 1095, 1102, 1109]
print(has_permission(1088, permitted_users))
这种方式需要逐个遍历列表,时间复杂度为 O(n)。
推荐写法:
def has_permission(user_id, permitted_users):
# permitted_users 现在是用户ID集合
return user_id in permitted_users
permitted_users = {1001, 1023, 1052, 1076, 1088, 1095, 1102, 1109}
print(has_permission(1088, permitted_users))
这里使用集合(花括号表示),集合内部使用哈希表,查找速度极快,时间复杂度为 O(1)。
说明:对于小型集合差别可能不大,但数据变大时,集合或字典查找效率优势明显。
4. 用生成器高效处理大数据
在处理大型数据集时,如果一次性将所有数据加载进内存,程序可能会变慢甚至崩溃。生成器可以按需逐个生成数据项,大大节省内存。
不推荐的写法:
def find_errors(log_file):
with open(log_file, 'r') as file:
lines = file.readlines()
error_messages = []
for line in lines:
if '[ERROR]' in line:
timestamp = line.split('[ERROR]')[0].strip()
message = line.split('[ERROR]')[1].strip()
error_messages.append((timestamp, message))
return error_messages
该方法会一次性将整个文件读入内存,文件大时易耗尽内存。
推荐写法:
def find_errors(log_file):
with open(log_file, 'r') as file:
for line in file:
if '[ERROR]' in line:
timestamp = line.split('[ERROR]')[0].strip()
message = line.split('[ERROR]')[1].strip()
yield (timestamp, message)
# 用法示例
for timestamp, message in find_errors('application.log'):
print(f"Error at {timestamp}: {message}")
这里使用生成器(yield),每次只处理一行数据,内存占用极低。
优点:
无论文件大小,内存占用都很低
可以实时获得结果,无需等待全部处理完
可以按需提前终止处理,节省时间
生成器非常适合处理大文件、网络流、数据库查询等大批量数据。
5. 避免在循环中重复执行昂贵操作
优化循环性能的一个简单方法是,把与循环变量无关、计算量大的操作移到循环外,只执行一次。
不推荐的写法:
import re
from datetime import datetime
def find_recent_errors(logs):
recent_errors = []
for log in logs:
# 每次循环都编译正则表达式
timestamp_pattern = re.compile(r'\[(.*?)\]')
timestamp_match = timestamp_pattern.search(log)
if timestamp_match and '[ERROR]' in log:
# 每次循环都获取当前时间
log_time = datetime.strptime(timestamp_match.group(1), '%Y-%m-%d %H:%M:%S')
current_time = datetime.now()
time_diff = (current_time - log_time).total_seconds() / 3600
if time_diff <= 24:
recent_errors.append(log)
return recent_errors
不必要地反复编译正则和获取当前时间,浪费资源。
推荐写法:
import re
from datetime import datetime
def find_recent_errors(logs):
recent_errors = []
# 在循环外编译正则和获取当前时间
timestamp_pattern = re.compile(r'\[(.*?)\]')
current_time = datetime.now()
for log in logs:
timestamp_match = timestamp_pattern.search(log)
if timestamp_match and '[ERROR]' in log:
log_time = datetime.strptime(timestamp_match.group(1), '%Y-%m-%d %H:%M:%S')
time_diff = (current_time - log_time).total_seconds() / 3600
if time_diff <= 24:
recent_errors.append(log)
return recent_errors
循环外只执行一次,提升效率,特别是循环次数多时效果更明显。
6. 避免用 += 拼接字符串
循环中用+=方式拼接字符串效率极低。每次操作都会创建新的字符串对象,随着字符串变长,代价越来越高。更高效的做法是用列表收集各部分,最后一次性拼接。
不推荐的写法:
def generate_html_report(data_points):
html = "<html><body><h1>Data Report</h1><ul>"
for point in data_points:
html += f"<li>{point['name']}: {point['value']} ({point['timestamp']})</li>"
html += "</ul></body></html>"
return html
字符串不可变,每次拼接都要新建对象,效率低下。
推荐写法:
def generate_html_report(data_points):
parts = ["<html><body><h1>Data Report</h1><ul>"]
for point in data_points:
parts.append(f"<li>{point['name']}: {point['value']} ({point['timestamp']})</li>")
parts.append("</ul></body></html>")
return "".join(parts)
用列表收集片段,最后用"".join(parts)一步生成大字符串,效率高且易读。
总结
编写高效的 Python 代码并不需要高深的知识,更多是用对了方法。本文介绍的技巧聚焦于常用高效编程模式,能够显著提升代码性能:
用内置函数替代手动实现
用列表推导式实现高效转换
用集合和字典加速查找
用生成器高效处理大数据
将不变的昂贵操作移到循环外
用列表拼接字符串而非+=
记得:代码的可读性同样重要。幸运的是,很多高效写法也让代码更简洁、更易懂,让你的程序既高效又优雅。
希望这些技巧能帮你在成为更优秀 Python 程序员的路上更进一步。继续编码,加油!
领取专属 10元无门槛券
私享最新 技术干货