12 KiB
12 KiB
Python 快速参考
基本语法
变量与类型
# 动态类型
x = 5 # int
y = 3.14 # float
name = "Alice" # str
is_valid = True # bool
# 类型提示(可选,Python 3.5+)
def greet(name: str) -> str:
return f"Hello, {name}"
# 多重赋值
a, b, c = 1, 2, 3
x = y = z = 0
字符串
# 字符串创建
s = "hello"
s = 'hello'
s = """multi
line"""
# F-字符串(Python 3.6+)
name = "Alice"
age = 30
message = f"{name} is {age} years old"
# 常用方法
s.upper() # "HELLO"
s.lower() # "hello"
s.strip() # 移除空白字符
s.split(',') # 拆分为列表
s.replace('h', 'H') # "Hello"
s.startswith('he') # True
s.endswith('lo') # True
s.find('ll') # 2(索引,未找到返回 -1)
# 切片
s[0] # 'h'
s[-1] # 'o'
s[1:4] # 'ell'
s[::-1] # 'olleh'(反转)
列表
# 创建
nums = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# 常用操作
nums.append(6) # 添加到末尾
nums.insert(0, 0) # 在指定索引处插入
nums.remove(3) # 移除首次出现的元素
nums.pop() # 移除并返回最后一个元素
nums.pop(0) # 移除并返回指定索引的元素
nums.extend([7, 8]) # 添加多个元素
len(nums) # 长度
nums.sort() # 原地排序
sorted(nums) # 返回排序后的副本
nums.reverse() # 原地反转
nums[::-1] # 返回反转后的副本
# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
字典
# 创建
person = {'name': 'Alice', 'age': 30}
person = dict(name='Alice', age=30)
# 访问
name = person['name'] # 键不存在时抛出 KeyError
name = person.get('name') # 键不存在时返回 None
name = person.get('name', 'Unknown') # 指定默认值
# 修改
person['city'] = 'NYC' # 添加/更新
del person['age'] # 删除
age = person.pop('age', 0) # 删除并返回
# 迭代
for key in person:
print(key, person[key])
for key, value in person.items():
print(key, value)
# 字典推导式
squares = {x: x**2 for x in range(5)}
集合
# 创建
s = {1, 2, 3, 4, 5}
s = set([1, 2, 3, 3, 3]) # {1, 2, 3}
# 操作
s.add(6) # 添加元素
s.remove(3) # 移除(元素不存在时抛出 KeyError)
s.discard(3) # 移除(元素不存在时不报错)
s.union({4, 5, 6}) # {1, 2, 3, 4, 5, 6}
s.intersection({3, 4}) # {3, 4}
s.difference({3, 4}) # {1, 2, 5}
控制流
If-Elif-Else
x = 10
if x > 0:
print("Positive")
elif x < 0:
print("Negative")
else:
print("Zero")
# 三元表达式
result = "Positive" if x > 0 else "Non-positive"
循环
# For 循环
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8
print(i)
for item in [1, 2, 3]:
print(item)
# Enumerate(索引 + 值)
for i, val in enumerate(['a', 'b', 'c']):
print(f"{i}: {val}")
# While 循环
i = 0
while i < 5:
print(i)
i += 1
# Break 和 continue
for i in range(10):
if i == 3:
continue # 跳过 3
if i == 8:
break # 在 8 处停止
print(i)
函数
基本函数
def greet(name):
return f"Hello, {name}"
# 默认参数
def greet(name="World"):
return f"Hello, {name}"
# 多个返回值
def divide(a, b):
return a // b, a % b # 返回元组
quotient, remainder = divide(10, 3)
# *args 和 **kwargs
def print_all(*args):
for arg in args:
print(arg)
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_all(1, 2, 3)
print_info(name="Alice", age=30)
Lambda 函数
# 匿名函数
square = lambda x: x ** 2
add = lambda x, y: x + y
# 常用于 map、filter、sorted
nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
sorted_tuples = sorted([(1, 'c'), (2, 'a')], key=lambda x: x[1])
面向对象编程
类
class Person:
# 类变量
species = "Homo sapiens"
def __init__(self, name, age):
# 实例变量
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
def __str__(self):
return f"Person(name={self.name}, age={self.age})"
def __repr__(self):
return f"Person('{self.name}', {self.age})"
# 使用
p = Person("Alice", 30)
print(p.greet())
print(p) # 使用 __str__
继承
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
dog = Dog("Buddy")
print(dog.speak()) # Buddy says Woof!
属性
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 cannot be negative")
self._radius = value
@property
def area(self):
return 3.14159 * self._radius ** 2
# 使用
c = Circle(5)
print(c.area) # 78.53975
c.radius = 10 # 使用 setter
特殊方法(魔术方法)
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
def __len__(self):
return 2
def __getitem__(self, index):
return [self.x, self.y][index]
v1 = Vector(1, 2)
v2 = Vector(3, 4)
v3 = v1 + v2 # 使用 __add__
print(v3) # 使用 __str__
文件 I/O
# 读取
with open('file.txt', 'r') as f:
content = f.read() # 读取整个文件
# 或
lines = f.readlines() # 读取为行列表
# 或
for line in f: # 逐行迭代
print(line.strip())
# 写入
with open('file.txt', 'w') as f:
f.write("Hello\n")
f.writelines(["Line 1\n", "Line 2\n"])
# 追加
with open('file.txt', 'a') as f:
f.write("New line\n")
# JSON
import json
# 写入 JSON
data = {'name': 'Alice', 'age': 30}
with open('data.json', 'w') as f:
json.dump(data, f, indent=2)
# 读取 JSON
with open('data.json', 'r') as f:
data = json.load(f)
错误处理
# Try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Error: {e}")
else:
print("No errors") # 未发生异常时执行
finally:
print("Always runs") # 始终执行
# 抛出异常
def divide(a, b):
if b == 0:
raise ValueError("Divisor cannot be zero")
return a / b
# 自定义异常
class InvalidAgeError(Exception):
pass
def set_age(age):
if age < 0:
raise InvalidAgeError("Age cannot be negative")
常用库
Collections
from collections import Counter, defaultdict, deque
# Counter
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count = Counter(words)
print(count['apple']) # 3
print(count.most_common(2)) # [('apple', 3), ('banana', 2)]
# defaultdict
d = defaultdict(list)
d['key'].append(1) # 不会抛出 KeyError
# deque(双端队列)
q = deque([1, 2, 3])
q.append(4) # 从右侧添加
q.appendleft(0) # 从左侧添加
q.pop() # 从右侧移除
q.popleft() # 从左侧移除
Itertools
from itertools import combinations, permutations, product
# 组合
list(combinations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 3)]
# 排列
list(permutations([1, 2, 3], 2)) # [(1, 2), (1, 3), (2, 1), ...]
# 笛卡尔积
list(product([1, 2], ['a', 'b'])) # [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
Functools
from functools import lru_cache, reduce
# 记忆化
@lru_cache(maxsize=None)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
# Reduce
from functools import reduce
product = reduce(lambda x, y: x * y, [1, 2, 3, 4]) # 24
列表/字典/集合推导式
# 列表推导式
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]
nested = [[i for i in range(3)] for j in range(3)]
# 字典推导式
squares_dict = {x: x**2 for x in range(5)}
filtered = {k: v for k, v in squares_dict.items() if v > 5}
# 集合推导式
unique_lengths = {len(word) for word in ['apple', 'banana', 'kiwi']}
# 生成器表达式(内存高效)
sum_of_squares = sum(x**2 for x in range(1000000))
有用的内置函数
# any, all
any([False, True, False]) # True(至少一个为 True)
all([True, True, True]) # True(全部为 True)
# zip
names = ['Alice', 'Bob']
ages = [30, 25]
for name, age in zip(names, ages):
print(f"{name}: {age}")
# enumerate
for i, val in enumerate(['a', 'b', 'c']):
print(f"{i}: {val}")
# map, filter
nums = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))
# sorted, reversed
sorted([3, 1, 2]) # [1, 2, 3]
sorted([3, 1, 2], reverse=True) # [3, 2, 1]
list(reversed([1, 2, 3])) # [3, 2, 1]
# max, min, sum
max([1, 5, 3]) # 5
min([1, 5, 3]) # 1
sum([1, 2, 3]) # 6
常用惯用法
变量交换
a, b = b, a
三元运算符
result = "Even" if x % 2 == 0 else "Odd"
字典默认值
value = my_dict.get('key', default_value)
带起始值的 Enumerate
for i, val in enumerate(items, start=1):
print(f"{i}. {val}")
解包
first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2,3,4], last=5
上下文管理器
with open('file.txt') as f:
data = f.read()
# 文件自动关闭
最佳实践
1. PEP 8 风格指南
# 使用 4 个空格缩进
# 变量和函数使用 snake_case
# 类使用 PascalCase
# 常量使用大写
def calculate_total(items):
DISCOUNT_RATE = 0.1
total = sum(items)
return total * (1 - DISCOUNT_RATE)
2. 列表推导式 vs 循环
# 简单转换优先使用推导式
squares = [x**2 for x in range(10)]
# 复杂逻辑使用循环
results = []
for x in range(10):
if x % 2 == 0:
result = process_even(x)
else:
result = process_odd(x)
results.append(result)
3. None 用 is,值比较用 ==
if value is None: # 正确
if value == None: # 也能工作但不推荐
4. EAFP 与 LBYL
# 请求原谅比获得许可更容易(Pythonic 风格)
try:
value = my_dict['key']
except KeyError:
value = default
# 三思而后行(不够 Pythonic)
if 'key' in my_dict:
value = my_dict['key']
else:
value = default
常见陷阱
1. 可变默认参数
# 错误
def append_to(element, lst=[]):
lst.append(element)
return lst
# 所有调用共享同一个列表!
print(append_to(1)) # [1]
print(append_to(2)) # [1, 2] — 不符合预期!
# 正确
def append_to(element, lst=None):
if lst is None:
lst = []
lst.append(element)
return lst
2. 闭包延迟绑定
# 错误
funcs = [lambda: i for i in range(5)]
print([f() for f in funcs]) # [4, 4, 4, 4, 4]
# 正确
funcs = [lambda i=i: i for i in range(5)]
print([f() for f in funcs]) # [0, 1, 2, 3, 4]
3. 遍历列表时修改
# 错误
lst = [1, 2, 3, 4, 5]
for item in lst:
if item % 2 == 0:
lst.remove(item) # 可能跳过元素
# 正确
lst = [item for item in lst if item % 2 != 0]
Python 3.10+ 特性
结构化模式匹配
def process_command(command):
match command.split():
case ["quit"]:
return "Quitting"
case ["load", filename]:
return f"Loading {filename}"
case ["save", filename]:
return f"Saving {filename}"
case _:
return "Unknown command"
联合类型
def greet(name: str | None = None) -> str:
if name is None:
return "Hello, stranger"
return f"Hello, {name}"