Python基础详解:数据容器、函数与注解
·
Python基础详解:数据容器、函数与注解
目录
数据容器
列表 (List)
列表是Python中最常用的数据容器之一,用于存储有序的元素集合。
基本操作
# 创建列表
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
# 访问元素
print(fruits[0]) # 输出: apple
# 修改元素
fruits[1] = "blueberry"
# 添加元素
fruits.append("orange") # 末尾添加
fruits.insert(1, "grape") # 指定位置插入
# 删除元素
fruits.remove("cherry") # 按值删除
del fruits[0] # 按索引删除
# 切片操作
print(fruits[1:3]) # 输出: ['grape', 'blueberry']
列表推导式
# 基本列表推导式
squares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 带条件的列表推导式
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # 输出: [0, 4, 16, 36, 64]
# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
常用方法
# 排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort() # 原地排序
print(numbers) # 输出: [1, 1, 2, 3, 4, 5, 6, 9]
# 反转
numbers.reverse()
print(numbers) # 输出: [9, 6, 5, 4, 3, 2, 1, 1]
# 查找
print(numbers.index(5)) # 输出: 2
print(numbers.count(1)) # 输出: 2
# 长度和包含检查
print(len(numbers)) # 输出: 8
print(5 in numbers) # 输出: True
元组 (Tuple)
元组是不可变的有序序列,一旦创建就不能修改。
基本操作
# 创建元组
coordinates = (10, 20)
colors = ("red", "green", "blue")
single = (42,) # 单元素元组需要逗号
# 访问元素
print(coordinates[0]) # 输出: 10
# 切片
print(colors[0:2]) # 输出: ('red', 'green')
# 元组解包
x, y = coordinates
print(f"x: {x}, y: {y}") # 输出: x: 10, y: 20
元组的不可变性
# 元组不能修改
point = (10, 20)
# point[0] = 30 # 这会引发 TypeError
# 但是可以包含可变对象
mixed = (1, [2, 3], 4)
mixed[1][0] = 99 # 这是允许的
print(mixed) # 输出: (1, [99, 3], 4)
命名元组
from collections import namedtuple
# 定义命名元组
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 输出: 10 20
# 命名元组的特性
print(p._fields) # 输出: ('x', 'y')
print(p._asdict()) # 输出: {'x': 10, 'y': 20}
字典 (Dictionary)
字典是键值对的集合,用于存储关联数据。
基本操作
# 创建字典
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# 访问元素
print(person["name"]) # 输出: Alice
print(person.get("email", "N/A")) # 输出: N/A
# 添加/修改元素
person["email"] = "alice@example.com"
person["age"] = 26
# 删除元素
del person["city"]
person.pop("email")
# 检查键是否存在
print("name" in person) # 输出: True
字典推导式
# 基本字典推导式
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 带条件的字典推导式
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares) # 输出: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
字典方法
# 获取所有键/值/键值对
keys = person.keys()
values = person.values()
items = person.items()
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
# 更新字典
person.update({"age": 27, "job": "Engineer"})
# 设置默认值
person.setdefault("hobbies", [])
集合 (Set)
集合是无序、不重复的元素集合。
基本操作
# 创建集合
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 4, 5]) # 从列表创建
# 添加元素
fruits.add("orange")
# 删除元素
fruits.remove("banana")
fruits.discard("grape") # 如果不存在不会报错
# 检查元素
print("apple" in fruits) # 输出: True
# 长度
print(len(fruits)) # 输出: 3
集合运算
# 并集
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2) # 输出: {1, 2, 3, 4, 5}
# 交集
print(set1 & set2) # 输出: {3}
# 差集
print(set1 - set2) # 输出: {1, 2}
# 对称差集
print(set1 ^ set2) # 输出: {1, 2, 4, 5}
集合推导式
# 基本集合推导式
squares_set = {x**2 for x in range(-5, 6)}
print(squares_set) # 输出: {0, 1, 4, 9, 16, 25}
函数
函数定义与调用
# 基本函数定义
def greet(name):
"""向某人打招呼"""
return f"Hello, {name}!"
# 调用函数
message = greet("Alice")
print(message) # 输出: Hello, Alice!
参数类型
位置参数
def add(a, b):
return a + b
result = add(3, 5) # 位置参数
print(result) # 输出: 8
默认参数
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"
print(greet("Alice")) # 输出: Hello, Alice!
print(greet("Alice", "Hi")) # 输出: Hi, Alice!
关键字参数
def person_info(name, age, city):
return f"{name} is {age} years old from {city}"
# 关键字参数
info = person_info(age=25, name="Bob", city="New York")
print(info) # 输出: Bob is 25 years old from New York
可变参数
# *args - 接受任意数量的位置参数
def sum_all(*args):
return sum(args)
print(sum_all(1, 2, 3, 4, 5)) # 输出: 15
# **kwargs - 接受任意数量的关键字参数
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")
仅关键字参数
def create_user(name, *, age, email):
return {"name": name, "age": age, "email": email}
# age和email必须作为关键字参数传递
user = create_user("Alice", age=25, email="alice@example.com")
print(user)
返回值
# 单个返回值
def square(x):
return x ** 2
# 多个返回值
def getMinMax(numbers):
return min(numbers), max(numbers)
min_val, max_val = getMinMax([1, 2, 3, 4, 5])
print(f"Min: {min_val}, Max: {max_val}") # 输出: Min: 1, Max: 5
作用域
# 全局变量
global_var = "I'm global"
def outer():
# 外层函数变量
outer_var = "I'm outer"
def inner():
# 内层函数变量
inner_var = "I'm inner"
print(global_var)
print(outer_var)
print(inner_var)
inner()
outer()
装饰器
# 基本装饰器
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start:.4f} seconds")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
return "Done"
result = slow_function()
print(result)
# 带参数的装饰器
def repeat(n):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello!")
say_hello()
注解
类型注解
类型注解用于指定变量、函数参数和返回值的类型。
基本类型注解
# 变量注解
name: str = "Alice"
age: int = 25
height: float = 5.6
is_student: bool = True
# 容器类型注解
numbers: list[int] = [1, 2, 3]
coordinates: tuple[float, float] = (10.0, 20.0)
person: dict[str, int] = {"age": 25, "score": 100}
unique_numbers: set[int] = {1, 2, 3}
函数注解
# 基本函数注解
def greet(name: str) -> str:
return f"Hello, {name}!"
# 多参数函数注解
def calculate(x: int, y: int, operation: str = "add") -> int:
if operation == "add":
return x + y
elif operation == "multiply":
return x * y
else:
raise ValueError("Invalid operation")
# 复杂类型注解
from typing import List, Dict, Tuple, Optional, Union
def process_data(
data: List[int],
config: Dict[str, Union[str, int]],
callback: Optional[callable] = None
) -> Tuple[List[int], bool]:
# 处理数据
result = [x * 2 for x in data]
success = len(result) > 0
if callback:
callback(result)
return result, success
变量注解
# 使用 typing 模块
from typing import List, Dict, Set, Tuple, Optional, Union
# 列表注解
fruits: List[str] = ["apple", "banana", "cherry"]
# 字典注解
scores: Dict[str, int] = {"Alice": 95, "Bob": 87}
# 集合注解
unique_numbers: Set[int] = {1, 2, 3, 4, 5}
# 元组注解
point: Tuple[float, float] = (10.0, 20.0)
# 可选类型
def find_user(user_id: int) -> Optional[str]:
if user_id == 1:
return "Alice"
return None
# 联合类型
def process(value: Union[int, str]) -> str:
return str(value)
类型检查工具
# 使用 mypy 进行类型检查
# 安装: pip install mypy
# 运行: mypy your_script.py
# 示例代码 (save as example.py)
def add(a: int, b: int) -> int:
return a + b
# 类型错误示例
result: str = add(1, 2) # mypy 会报告类型错误
# 使用类型别名
from typing import List, Tuple
Vector = List[float]
Matrix = List[Vector]
def dot_product(v1: Vector, v2: Vector) -> float:
return sum(x * y for x, y in zip(v1, v2))
# 使用 TypedDict
from typing import TypedDict
class PersonDict(TypedDict):
name: str
age: int
email: str
person: PersonDict = {
"name": "Alice",
"age": 25,
"email": "alice@example.com"
}
总结
数据容器对比
| 容器类型 | 可变性 | 有序性 | 重复元素 | 主要用途 |
|---|---|---|---|---|
| 列表 | 可变 | 有序 | 允许 | 存储有序数据集合 |
| 元组 | 不可变 | 有序 | 允许 | 存储不变的数据集合 |
| 字典 | 可变 | 有序 | 键唯一 | 存储键值对关联数据 |
| 集合 | 可变 | 无序 | 不允许 | 存储唯一元素集合 |
函数最佳实践
- 单一职责原则: 每个函数只做一件事
- 合理命名: 使用描述性的函数名
- 文档字符串: 为函数添加说明
- 类型注解: 提高代码可读性和可维护性
- 错误处理: 使用适当的异常处理
注解最佳实践
- 始终使用类型注解: 提高代码可读性
- 使用类型别名: 简化复杂类型
- 定期运行类型检查: 使用 mypy 等工具
- 保持注解更新: 确保注解与实际代码一致
更多推荐
所有评论(0)