Python编程的100个小技巧
Python是一种功能强大且易于学习的编程语言。以下是100个Python编程的小技巧,每个技巧都附有代码案例,帮助你更高效地编写Python代码。
文章目录
- 1. 使用列表推导式
- 2. 使用生成器表达式节省内存
- 3. 用`enumerate`获取索引和值
- 4. 使用`zip`函数并行迭代
- 5. 使用`*`解包
- 6. 用`collections.Counter`计数
- 7. 使用`defaultdict`处理缺失键
- 8. 使用`set`去重
- 9. 使用`itertools`生成排列和组合
- 10. 用`functools.lru_cache`缓存函数结果
- 11. 使用`contextlib`管理上下文
- 12. 用`with`语句简化资源管理
- 13. 使用`try…except`捕获异常
- 14. 用`finally`确保资源释放
- 15. 使用`assert`进行调试
- 16. 用`logging`记录日志
- 17. 使用`datetime`处理日期和时间
- 18. 使用`timeit`进行性能测试
- 19. 用`shutil`进行文件操作
- 20. 使用`glob`查找文件
- 21. 用`subprocess`执行系统命令
- 22. 使用`argparse`解析命令行参数
- 23. 使用`json`处理JSON数据
- 24. 使用`re`进行正则表达式匹配
- 25. 用`pandas`处理数据
- 26. 使用`numpy`进行数值计算
- 27. 用`matplotlib`绘图
- 28. 使用`requests`进行HTTP请求
- 29. 使用`BeautifulSoup`解析HTML
- 30. 用`selenium`进行网页自动化
- 31. 使用`threading`进行多线程编程
- 32. 用`multiprocessing`进行多进程编程
- 33. 使用`asyncio`进行
- 34. 使用`dataclasses`简化类定义
- 35. 用`property`定义属性
- 36. 使用`__slots__`优化内存使用
- 37. 用`__repr__`和`__str__`定义字符串表示
- 38. 使用`super`调用父类方法
- 39. 用`isinstance`检查对象类型
- 40. 使用`issubclass`检查类继承关系
- 41. 使用`abc`模块定义抽象基类
- 42. 使用`copy`模块进行深拷贝
- 43. 使用`@staticmethod`和`@classmethod`
- 44. 使用`itertools.chain`连接迭代器
- 45. 用`itertools.islice`切片迭代器
- 46. 使用`namedtuple`创建具名元组
- 47. 用`deque`进行高效的队列操作
- 48. 使用`OrderedDict`保持字典顺序
- 49. 用`ChainMap`组合多个字典
- 50. 使用`heapq`实现堆队列
- 51. 用`bisect`进行二分查找
- 52. 使用`statistics`进行统计计算
- 53. 用`fractions`处理分数
- 54. 使用`decimal`进行高精度计算
- 55. 用`uuid`生成唯一标识符
- 56. 使用`secrets`生成安全随机数
- 57. 使用`hashlib`进行哈希计算
- 58. 用`hmac`进行消息认证
- 59. 使用`socket`进行网络编程
- 60. 用`email`构建和解析电子邮件
- 61. 使用`imaplib`接收邮件
- 62. 使用`smtplib`发送邮件
- 63. 用`csv`处理CSV文件
- 64. 使用`sqlite3`进行数据库操作
- 65. 用`pickle`进行对象序列化
- 66. 使用`xml.etree.ElementTree`解析XML
- 67. 用`configparser`解析配置文件
- 68. 使用`unittest`进行单元测试
- 69. 使用`doctest`进行文档测试
- 70. 用`time`模块进行时间操作
- 71. 使用`calendar`处理日历
- 72. 用`random`生成随机数
- 73. 使用`math`进行数学计算
- 74. 用`statistics`进行统计计算
- 75. 使用`typing`进行类型注解
- 76. 使用`functools.partial`简化函数调用
- 77. 使用`functools.wraps`保留装饰器原信息
- 78. 用`dataclasses.field`定义默认值
- 79. 使用`weakref`避免循环引用
- 80. 使用`contextlib.closing`确保资源关闭
- 81. 用`tempfile`创建临时文件
- 82. 使用`pdb`进行调试
- 83. 使用`trace`跟踪程序执行
- 84. 用`cProfile`进行性能分析
- 85. 使用`line_profiler`分析代码行
- 86. 使用`memory_profiler`分析内存使用
- 87. 用`tracemalloc`分析内存分配
- 88. 使用`asyncio`进行异步编程
- 89. 使用`multiprocessing`进行多进程编程
- 90. 用`threading`进行多线程编程
- 91. 使用`subprocess`执行子进程
- 92. 用`shutil`操作文件
- 93. 使用`pathlib`处理文件路径
- 94. 使用`tarfile`压缩和解压缩文件
- 95. 用`zipfile`压缩和解压缩文件
- 96. 使用`bz2`进行数据压缩
- 97. 使用`gzip`进行数据压缩
- 98. 用`lzma`进行数据压缩
- 99. 使用`concurrent.futures`进行并行编程
- 100. 用`asyncio`和`aiohttp`进行异步HTTP请求
1. 使用列表推导式
列表推导式可以让你用一行代码创建一个新的列表。
squares = [x**2 for x in range(10)]
print(squares)
2. 使用生成器表达式节省内存
生成器表达式不会一次性生成所有元素,因此在处理大数据时更节省内存。
squares_gen = (x**2 for x in range(10))
for square in squares_gen:
print(square)
3. 用enumerate
获取索引和值
enumerate
函数让你在迭代列表时同时获取索引和值。
names = ["Alice", "Bob", "Charlie"]
for index, name in enumerate(names):
print(index, name)
4. 使用zip
函数并行迭代
zip
函数可以让你并行迭代多个可迭代对象。
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(name, age)
5. 使用*
解包
解包可以方便地传递参数或合并列表。
def multiply(a, b, c):
return a * b * c
nums = [2, 3, 4]
result = multiply(*nums)
print(result)
6. 用collections.Counter
计数
Counter
是一个方便的计数工具。
from collections import Counter
words = ["apple", "banana", "apple", "orange", "banana", "banana"]
word_count = Counter(words)
print(word_count)
7. 使用defaultdict
处理缺失键
defaultdict
可以避免KeyError异常。
from collections import defaultdict
d = defaultdict(int)
d['apple'] += 1
print(d)
8. 使用set
去重
集合类型自动去重。
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers)
print(unique_numbers)
9. 使用itertools
生成排列和组合
itertools
模块提供了排列和组合的生成器。
from itertools import permutations, combinations
items = [1, 2, 3]
perms = list(permutations(items))
combs = list(combinations(items, 2))
print("Permutations:", perms)
print("Combinations:", combs)
10. 用functools.lru_cache
缓存函数结果
lru_cache
可以缓存函数的结果,提高性能。
from functools import lru_cache
@lru_cache(maxsize=32)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print([fib(n) for n in range(10)])
11. 使用contextlib
管理上下文
contextlib
可以简化上下文管理器的实现。
from contextlib import contextmanager
@contextmanager
def open_file(name):
f = open(name, 'w')
try:
yield f
finally:
f.close()
with open_file('test.txt') as f:
f.write('Hello, World!')
12. 用with
语句简化资源管理
with
语句可以确保资源正确释放。
with open('test.txt', 'r') as file:
content = file.read()
print(content)
13. 使用try...except
捕获异常
捕获并处理异常以避免程序崩溃。
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
14. 用finally
确保资源释放
finally
块确保代码块中的资源被释放。
try:
f = open('test.txt', 'r')
finally:
f.close()
15. 使用assert
进行调试
assert
语句用于在调试时检查条件。
def square(x):
assert x >= 0, "x should be non-negative"
return x * x
print(square(4))
16. 用logging
记录日志
logging
模块提供了灵活的日志记录功能。
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an info message")
17. 使用datetime
处理日期和时间
datetime
模块用于日期和时间操作。
from datetime import datetime
now = datetime.now()
print(now.strftime('%Y-%m-%d %H:%M:%S'))
18. 使用timeit
进行性能测试
timeit
模块用于测量小段代码的执行时间。
import timeit
print(timeit.timeit('"-".join(str(n) for n in range(100))', number=10000))
19. 用shutil
进行文件操作
shutil
模块提供了高级的文件操作功能。
import shutil
shutil.copy('test.txt', 'test_copy.txt')
20. 使用glob
查找文件
glob
模块用于查找符合特定模式的文件。
import glob
files = glob.glob('*.txt')
print(files)
21. 用subprocess
执行系统命令
subprocess
模块用于执行系统命令。
import subprocess
result = subprocess.run(['echo', 'Hello, World!'], capture_output=True, text=True)
print(result.stdout)
22. 使用argparse
解析命令行参数
argparse
模块用于解析命令行参数。
import argparse
parser = argparse.ArgumentParser(description='Sample argparse script')
parser.add_argument('name', type=str, help='Your name')
args = parser.parse_args()
print(f"Hello, {args.name}!")
23. 使用json
处理JSON数据
json
模块用于解析和生成JSON数据。
import json
data = {'name': 'Alice', 'age': 25}
json_str = json.dumps(data)
print(json_str)
data = json.loads(json_str)
print(data)
24. 使用re
进行正则表达式匹配
re
模块提供了正则表达式的支持。
import re
pattern = re.compile(r'\d+')
result = pattern.findall('There are 123 apples and 456 oranges.')
print(result)
25. 用pandas
处理数据
pandas
是一个强大的数据处理库。
import pandas as pd
data = {'name': ['Alice', 'Bob'], 'age': [25, 30]}
df = pd.DataFrame(data)
print(df)
26. 使用numpy
进行数值计算
numpy
是一个高效的数值计算库。
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2)
27. 用matplotlib
绘图
matplotlib
是一个强大的绘图库。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.show()
28. 使用requests
进行HTTP请求
requests
模块提供了简便的HTTP请求功能。
import requests
response = requests.get('http://api.github.com')
print(response.json())
29. 使用BeautifulSoup
解析HTML
BeautifulSoup
用于解析HTML和XML文档。
from bs4 import BeautifulSoup
html = 'Hello, World!
'
soup = BeautifulSoup(html, 'html.parser')
print(soup.h1.text)
30. 用selenium
进行网页自动化
selenium
用于进行网页自动化操作。
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.python.org')
print(driver.title)
driver.quit()
31. 使用threading
进行多线程编程
threading
模块用于多线程编程。
import threading
def print_numbers():
for i in range(10):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()
32. 用multiprocessing
进行多进程编程
multiprocessing
模块用于多进程编程。
import multiprocessing
def print_numbers():
for i in range(10):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
process.join()
33. 使用asyncio
进行
异步编程
asyncio
模块用于异步编程。
import asyncio
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(1)
asyncio.run(print_numbers())
34. 使用dataclasses
简化类定义
dataclasses
模块简化了类的定义。
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
person = Person('Alice', 25)
print(person)
35. 用property
定义属性
property
装饰器用于定义属性。
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError("Radius must be non-negative")
self._radius = value
circle = Circle(5)
print(circle.radius)
circle.radius = 10
print(circle.radius)
36. 使用__slots__
优化内存使用
__slots__
可以优化内存使用。
class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
point = Point(1, 2)
print(point.x, point.y)
37. 用__repr__
和__str__
定义字符串表示
__repr__
和__str__
定义对象的字符串表示。
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person(name={self.name}, age={self.age})"
def __str__(self):
return f"{self.name}, {self.age} years old"
person = Person('Alice', 25)
print(repr(person))
print(str(person))
38. 使用super
调用父类方法
super
函数用于调用父类方法。
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
super().speak()
print("Dog barks")
dog = Dog()
dog.speak()
39. 用isinstance
检查对象类型
isinstance
函数用于检查对象类型。
print(isinstance(5, int))
print(isinstance("hello", str))
40. 使用issubclass
检查类继承关系
issubclass
函数用于检查类的继承关系。
class Animal:
pass
class Dog(Animal):
pass
print(issubclass(Dog, Animal))
41. 使用abc
模块定义抽象基类
abc
模块用于定义抽象基类。
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Bark")
dog = Dog()
dog.speak()
42. 使用copy
模块进行深拷贝
copy
模块提供了深拷贝功能。
import copy
original = [1, 2, [3, 4]]
deep_copied = copy.deepcopy(original)
deep_copied[2][0] = 99
print(original)
print(deep_copied)
43. 使用@staticmethod
和@classmethod
静态方法和类方法可以通过装饰器定义。
class MyClass:
@staticmethod
def static_method():
print("Static method called")
@classmethod
def class_method(cls):
print("Class method called")
MyClass.static_method()
MyClass.class_method()
44. 使用itertools.chain
连接迭代器
itertools.chain
用于连接多个迭代器。
from itertools import chain
a = [1, 2, 3]
b = [4, 5, 6]
combined = list(chain(a, b))
print(combined)
45. 用itertools.islice
切片迭代器
itertools.islice
用于切片迭代器。
from itertools import islice
result = list(islice(range(10), 2, 8, 2))
print(result)
46. 使用namedtuple
创建具名元组
collections.namedtuple
用于创建具名元组。
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(1, 2)
print(p.x, p.y)
47. 用deque
进行高效的队列操作
collections.deque
是高效的双端队列。
from collections import deque
d = deque([1, 2, 3])
d.append(4)
d.appendleft(0)
print(d)
48. 使用OrderedDict
保持字典顺序
collections.OrderedDict
可以保持字典的插入顺序。
from collections import OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
print(od)
49. 用ChainMap
组合多个字典
collections.ChainMap
用于组合多个字典。
from collections import ChainMap
a = {'x': 1, 'y': 2}
b = {'y': 3, 'z': 4}
cm = ChainMap(a, b)
print(cm['x'])
print(cm['y'])
50. 使用heapq
实现堆队列
heapq
模块提供了堆队列实现。
import heapq
heap = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapq.heapify(heap)
heapq.heappush(heap, -5)
print(heapq.heappop(heap))
51. 用bisect
进行二分查找
bisect
模块用于二分查找和插入。
import bisect
a = [1, 3, 4, 4, 4, 6, 7]
print(bisect.bisect_left(a, 4))
print(bisect.bisect_right(a, 4))
52. 使用statistics
进行统计计算
statistics
模块提供了统计计算功能。
import statistics
data = [1, 2, 2, 3, 4]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.mode(data))
53. 用fractions
处理分数
fractions
模块用于处理分数。
from fractions import Fraction
f = Fraction(3, 4)
print(f)
print(f * 2)
54. 使用decimal
进行高精度计算
decimal
模块用于高精度浮点计算。
from decimal import Decimal
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b)
55. 用uuid
生成唯一标识符
uuid
模块用于生成唯一标识符。
import uuid
unique_id = uuid.uuid4()
print(unique_id)
56. 使用secrets
生成安全随机数
secrets
模块用于生成安全随机数。
import secrets
token = secrets.token_hex(16)
print(token)
57. 使用hashlib
进行哈希计算
hashlib
模块用于进行哈希计算。
import hashlib
data = 'Hello, World!'.encode('utf-8')
hash_object = hashlib.sha256(data)
hex_dig = hash_object.hexdigest()
print(hex_dig)
58. 用hmac
进行消息认证
hmac
模块用于消息认证码(MAC)操作。
import hmac
import hashlib
key = b'secret_key'
message = b'Hello, World!'
h = hmac.new(key, message, hashlib.sha256)
print(h.hexdigest())
59. 使用socket
进行网络编程
socket
模块用于网络编程。
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('www.python.org', 80))
s.sendall(b'GET / HTTP/1.1\r
Host: www.python.org\r
\r
')
response = s.recv(1024)
print(response)
s.close()
60. 用email
构建和解析电子邮件
email
模块用于构建和解析电子邮件。
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg['
Subject'] = 'Test Email'
msg.attach(MIMEText('This is a test email.', 'plain'))
print(msg.as_string())
61. 使用imaplib
接收邮件
imaplib
模块用于接收邮件。
import imaplib
mail = imaplib.IMAP4_SSL('imap.gmail.com')
mail.login('username', 'password')
mail.select('inbox')
result, data = mail.search(None, 'ALL')
mail_ids = data[0].split()
for mail_id in mail_ids:
result, msg_data = mail.fetch(mail_id, '(RFC822)')
raw_email = msg_data[0][1]
print(raw_email)
mail.logout()
62. 使用smtplib
发送邮件
smtplib
模块用于发送邮件。
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('This is a test email.')
msg['Subject'] = 'Test Email'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login('username', 'password')
server.send_message(msg)
63. 用csv
处理CSV文件
csv
模块用于处理CSV文件。
import csv
with open('data.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['name', 'age'])
writer.writerow(['Alice', 25])
writer.writerow(['Bob', 30])
with open('data.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
64. 使用sqlite3
进行数据库操作
sqlite3
模块用于操作SQLite数据库。
import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)')
c.execute("INSERT INTO users (name) VALUES ('Alice')")
conn.commit()
for row in c.execute('SELECT * FROM users'):
print(row)
conn.close()
65. 用pickle
进行对象序列化
pickle
模块用于对象的序列化和反序列化。
import pickle
data = {'name': 'Alice', 'age': 25}
with open('data.pkl', 'wb') as f:
pickle.dump(data, f)
with open('data.pkl', 'rb') as f:
loaded_data = pickle.load(f)
print(loaded_data)
66. 使用xml.etree.ElementTree
解析XML
xml.etree.ElementTree
模块用于解析XML。
import xml.etree.ElementTree as ET
xml_data = '''
'''
root = ET.fromstring(xml_data)
for child in root:
print(child.attrib)
67. 用configparser
解析配置文件
configparser
模块用于解析配置文件。
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config['DEFAULT']['ServerAliveInterval'])
68. 使用unittest
进行单元测试
unittest
模块用于单元测试。
import unittest
def add(a, b):
return a + b
class TestMathFunctions(unittest.TestCase):
def test_add(self):
self.assertEqual(add(1, 2), 3)
if __name__ == '__main__':
unittest.main()
69. 使用doctest
进行文档测试
doctest
模块用于测试文档中的代码。
def add(a, b):
"""
Adds two numbers.
>>> add(1, 2)
3
>>> add(-1, 1)
0
"""
return a + b
if __name__ == '__main__':
import doctest
doctest.testmod()
70. 用time
模块进行时间操作
time
模块提供了时间操作功能。
import time
print(time.time())
print(time.ctime())
time.sleep(1)
print("Slept for 1 second")
71. 使用calendar
处理日历
calendar
模块提供了日历相关的功能。
import calendar
print(calendar.month(2024, 6))
72. 用random
生成随机数
random
模块用于生成随机数。
import random
print(random.random())
print(random.randint(1, 10))
print(random.choice(['Alice', 'Bob', 'Charlie']))
73. 使用math
进行数学计算
math
模块提供了基本的数学计算功能。
import math
print(math.sqrt(16))
print(math.sin(math.pi / 2))
print(math.factorial(5))
74. 用statistics
进行统计计算
statistics
模块提供了统计计算功能。
import statistics
data = [1, 2, 2, 3, 4]
print(statistics.mean(data))
print(statistics.median(data))
print(statistics.mode(data))
75. 使用typing
进行类型注解
typing
模块提供了类型注解支持。
from typing import List, Dict
def greet(names: List[str]) -> None:
for name in names:
print(f"Hello, {name}")
greet(['Alice', 'Bob'])
76. 使用functools.partial
简化函数调用
functools.partial
可以简化函数的调用。
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(3))
77. 使用functools.wraps
保留装饰器原信息
functools.wraps
用于保留被装饰函数的原信息。
from functools import wraps
def my_decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
print("Calling decorated function")
return f(*args, **kwargs)
return wrapped
@my_decorator
def say_hello():
print("Hello")
say_hello()
78. 用dataclasses.field
定义默认值
dataclasses.field
用于定义字段默认值。
from dataclasses import dataclass, field
@dataclass
class Person:
name: str
age: int = 25
hobbies: list = field(default_factory=list)
person = Person('Alice')
print(person)
79. 使用weakref
避免循环引用
weakref
模块用于避免循环引用。
import weakref
class MyClass:
pass
obj = MyClass()
r = weakref.ref(obj)
print(r())
del obj
print(r())
80. 使用contextlib.closing
确保资源关闭
contextlib.closing
用于确保资源关闭。
from contextlib import closing
import sqlite3
with closing(sqlite3.connect('example.db')) as conn:
with conn:
c = conn.cursor()
c.execute('SELECT SQLITE_VERSION()')
print(c.fetchone())
81. 用tempfile
创建临时文件
tempfile
模块用于创建临时文件。
import tempfile
with tempfile.TemporaryFile() as temp:
temp.write(b'This is a temporary file')
temp.seek(0)
print(temp.read())
82. 使用pdb
进行调试
pdb
模块提供了交互式调试功能。
import pdb
def buggy_function(x, y):
result = x + y
pdb.set_trace()
return result
buggy_function(3, 5)
83. 使用trace
跟踪程序执行
trace
模块用于跟踪程序执行。
import trace
tracer = trace.Trace(count=False, trace=True)
tracer.run('print(sum(range(10)))')
84. 用cProfile
进行性能分析
cProfile
模块用于进行性能分析。
import cProfile
def slow_function():
for _ in range(10000):
sum(range(100))
cProfile.run('slow_function()')
85. 使用line_profiler
分析代码行
line_profiler
用于分析代码行性能。
# 需要安装line_profiler: pip install line_profiler
import line_profiler
def slow_function():
for _ in range(10000):
sum(range(100))
profiler = line_profiler.LineProfiler(slow_function)
profiler.enable_by_count()
slow_function()
profiler.print_stats()
86. 使用memory_profiler
分析内存使用
memory_profiler
用于分析内存使用。
# 需要安装memory_profiler: pip install memory_profiler
from memory_profiler import profile
@profile
def slow_function():
a = [i for i in range(10000)]
return a
slow_function()
87. 用tracemalloc
分析内存分配
tracemalloc
模块用于分析内存分配。
import tracemalloc
tracemalloc.start()
def slow_function():
a = [i for i in range(10000)]
return a
slow_function()
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno'):
print(stat)
88. 使用asyncio
进行异步编程
asyncio
模块用于异步编程。
import asyncio
async def print_numbers():
for i in range(10):
print(i)
await asyncio.sleep(1)
asyncio.run(print_numbers())
89. 使用multiprocessing
进行多进程编程
multiprocessing
模块用于多进程编程。
from multiprocessing import Process
def print_numbers():
for i in range(10):
print(i)
p = Process(target=print_numbers)
p.start()
p.join()
90. 用threading
进行多线程编程
threading
模块用于多线程编程。
import threading
def print_numbers():
for i in range(10):
print(i)
t = threading.Thread(target=print_numbers)
t.start()
t.join()
91. 使用subprocess
执行子进程
subprocess
模块用于执行子进程。
import subprocess
result = subprocess.run(['echo', 'Hello, World!'], capture_output=True, text=True)
print(result.stdout)
92. 用shutil
操作文件
shutil
模块用于高级文件操作。
import shutil
shutil.copy('source.txt', 'destination.txt')
shutil.move('source.txt', 'new_location.txt')
shutil.rmtree('directory_to_remove')
93. 使用pathlib
处理文件路径
pathlib
模块提供了面向对象的文件路径处理。
from pathlib import Path
path = Path('example.txt')
path.write_text('Hello, World!')
print(path.read_text())
94. 使用tarfile
压缩和解压缩文件
tarfile
模块用于处理tar文件。
import tarfile
with tarfile.open('archive.tar.gz', 'w:gz') as tar:
tar.add('example.txt')
with tarfile.open('archive.tar.gz', 'r:gz') as tar:
tar.extractall()
95. 用zipfile
压缩和解压缩文件
zipfile
模块用于处理zip文件。
import zipfile
with zipfile.ZipFile('archive.zip', 'w') as zipf:
zipf.write('example.txt')
with zipfile.ZipFile('archive.zip', 'r') as zipf:
zipf.extractall()
96. 使用bz2
进行数据压缩
bz2
模块用于数据压缩。
import bz2
data = b'This is the original text.'
compressed = bz2.compress(data)
decompressed = bz2.decompress(compressed)
print(decompressed)
97. 使用gzip
进行数据压缩
gzip
模块用于数据压缩。
import gzip
data = b'This is the original text.'
compressed = gzip.compress(data)
decompressed = gzip.decompress(compressed)
print(decompressed)
98. 用lzma
进行数据压缩
lzma
模块用于数据压缩。
import lzma
data = b'This is the original text.'
compressed = lzma.compress(data)
decompressed = lzma.decompress(compressed)
print(decompressed)
99. 使用concurrent.futures
进行并行编程
concurrent.futures
模块用于并行编程。
from concurrent.futures import ThreadPoolExecutor
def print_numbers():
for i in range(10):
print(i)
with ThreadPoolExecutor() as executor:
future = executor.submit(print_numbers)
future.result()
100. 用asyncio
和aiohttp
进行异步HTTP请求
aiohttp
模块用于异步HTTP请求。
import aiohttp
import asyncio
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
url = 'http://www.example.com'
html = await fetch(url)
print(html)
asyncio.run(main())