Python 中提升生产力的 12 个代码示例
1. 列表推导式:简化循环操作
列表推导式是一种快速创建列表的方法,使代码更加简洁。
# 普通方法
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
print(even_numbers) # 输出: [2, 4, 6, 8]
# 使用列表推导式
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers) # 输出: [2, 4, 6, 8]
2. 字典推导式:处理字典数据
字典推导式可以帮助快速创建或修改字典。
words = ['apple', 'banana', 'cherry']
word_lengths = {word: len(word) for word in words}
print(word_lengths) # 输出: {'apple': 5, 'banana': 6, 'cherry': 6}
3. 生成器表达式:节省内存
生成器表达式返回一个迭代器对象,节省内存。
# 列表推导式
squares = [x**2 for x in range(100000)]
print(squares[0:10])
# 生成器表达式
squares_gen = (x**2 for x in range(100000))
print(next(squares_gen)) # 输出: 0
print(next(squares_gen)) # 输出: 1
print(next(squares_gen)) # 输出: 4
4. 使用 enumerate()
:简化索引操作
enumerate()
函数可以在循环中获取元素和索引。
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
5. 使用 zip()
:并行迭代多个序列
zip()
函数用于并行遍历多个序列。
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old.")
6. 使用 itertools
模块:高效处理迭代操作
itertools.cycle()
可以创建一个无限循环的迭代器。
import itertools
colors = ['red', 'green', 'blue']
color_cycle = itertools.cycle(colors)
for _ in range(10):
print(next(color_cycle))
7. 使用 collections
模块:高效处理容器类型
Counter
可以轻松统计列表中元素的出现次数。
from collections import Counter
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
word_counts = Counter(words)
print(word_counts) # 输出: Counter({'apple': 3, 'banana': 2, 'cherry': 1})
8. 使用 functools
模块:提高函数灵活性
functools.partial()
用于部分应用函数的参数。
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, base=2)
print(square(exponent=3)) # 输出: 8
print(square(exponent=4)) # 输出: 16
9. 使用 contextlib
模块:管理上下文
contextlib.contextmanager
用于创建上下文管理器。
from contextlib import contextmanager
@contextmanager
def open_file(file_path, mode='r'):
file = open(file_path, mode)
try:
yield file
finally:
file.close()
with open_file('example.txt') as file:
content = file.read()
print(content)
10. 使用 pathlib
模块:简化文件路径操作
pathlib
提供了更直观的文件路径操作。
from pathlib import Path
directory = Path('test_directory')
directory.mkdir(exist_ok=True)
file_path = directory / 'example.txt'
file_path.touch()
with file_path.open('r') as file:
content = file.read()
print(content)
file_path.unlink()
directory.rmdir()
11. 使用 logging
模块:记录日志信息
logging
模块提供了方便的日志记录功能。
import logging
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s')
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
12. 使用 pandas
库:高效处理数据
pandas
提供了强大的数据处理功能。
import pandas as pd
data = pd.read_csv('example.csv')
print(data.head())
filtered_data = data[data['column_name'] > 10]
grouped_data = data.groupby('category').sum()
filtered_data.to_csv('filtered_example.csv', index=False)
实战案例:分析销售数据
使用 Pandas 处理销售数据的案例。
步骤 1:读取数据
sales_data = pd.read_csv('sales_data.csv')
print(sales_data.head())
步骤 2:筛选数据
threshold = 100000
filtered_sales = sales_data[sales_data['sales'] > threshold]
print(filtered_sales)
步骤 3:分组和聚合
monthly_sales = sales_data.groupby('month').sum()['sales']
print(monthly_sales)
步骤 4:保存结果
filtered_sales.to_csv('filtered_sales_data.csv', index=False)