全部学科
NodeJS全栈
nodejs
Python全栈
python
小程序首页
📅 2026-05-19 8 分钟 ✍️ juanwangdev

Python 复合类型注解

复合类型注解描述容器类型及其元素类型,精确表达数据结构。

List 列表注解

Python
from typing import List

# 列表元素类型
numbers: List[int] = [1, 2, 3]
names: List[str] = ['Alice', 'Bob']
prices: List[float] = [10.0, 20.0]

# 空列表注解
empty: List[int] = []

# 函数返回列表
def get_names() -> List[str]:
    return ['Alice', 'Bob']

# 函数参数列表
def process(items: List[int]) -> List[int]:
    return [x * 2 for x in items]

Dict 字典注解

Python
from typing import Dict

# 字典键值类型
scores: Dict[str, int] = {'Alice': 90, 'Bob': 85}
config: Dict[str, str] = {'host': 'localhost'}
mapping: Dict[int, str] = {1: 'one', 2: 'two'}

# 空字典
empty: Dict[str, int] = {}

# 函数返回字典
def get_config() -> Dict[str, str]:
    return {'debug': 'true'}

Tuple 元组注解

Python
from typing import Tuple

# 固定长度元组,指定每个元素类型
point: Tuple[int, int] = (10, 20)
record: Tuple[str, int, float] = ('Alice', 25, 90.5)

# 可变长度元组
numbers: Tuple[int, ...] = (1, 2, 3, 4, 5)

# 空元组
empty: Tuple[()] = ()

# 函数返回元组
def get_point() -> Tuple[int, int]:
    return (10, 20)

Set 集合注解

Python
from typing import Set

# 集合元素类型
unique_nums: Set[int] = {1, 2, 3}
tags: Set[str] = {'python', 'java'}
empty: Set[int] = set()

# FrozenSet
from typing import FrozenSet
constants: FrozenSet[int] = frozenset({1, 2, 3})

嵌套复合类型

Python
from typing import List, Dict, Tuple

# 嵌套列表
matrix: List[List[int]] = [[1, 2], [3, 4]]

# 嵌套字典
nested_dict: Dict[str, Dict[str, int]] = {
    'group1': {'Alice': 90}
}

# 字典列表
users: List[Dict[str, str]] = [
    {'name': 'Alice'},
    {'name': 'Bob'}
]

# 复杂嵌套
complex_type: Dict[str, List[Tuple[int, str]]] = {
    'data': [(1, 'a'), (2, 'b')]
}

Python 3.9+ 内置泛型

Python
# Python 3.9+ 可直接使用内置类型

# 无需导入 typing
numbers: list[int] = [1, 2, 3]       # 小写 list
scores: dict[str, int] = {'Alice': 90}
point: tuple[int, int] = (10, 20)
tags: set[str] = {'python'}

# 嵌套
matrix: list[list[int]] = [[1, 2], [3, 4]]

复合类型函数示例

Python
from typing import List, Dict, Tuple

def filter_positive(numbers: List[int]) -> List[int]:
    return [n for n in numbers if n > 0]

def merge_dicts(d1: Dict[str, int], d2: Dict[str, int]) -> Dict[str, int]:
    return {**d1, **d2}

def get_records() -> List[Tuple[str, int]]:
    return [('Alice', 25), ('Bob', 30)]

def process_matrix(matrix: List[List[int]]) -> List[List[int]]:
    return [[x * 2 for x in row] for row in matrix]

复合类型对比

类型typing 版本Python 3.9+ 版本
列表List[int]list[int]
字典Dict[str, int]dict[str, int]
元组Tuple[int, int]tuple[int, int]
集合Set[int]set[int]

默认值注解

Python
from typing import List, Dict

# 使用 typing 版本(兼容旧代码)
def process(items: List[int] = None) -> List[int]:
    if items is None:
        items = []
    return items

# Python 3.9+
def process_new(items: list[int] = []) -> list[int]:
    return items

类型注解最佳实践

Python
from typing import List, Dict

# 精确类型优于泛型
def process(data: List[int]):  # 好
    pass

def process(data: list):  # 不够精确
    pass

# 嵌套层次清晰
matrix: List[List[int]]  # 好
matrix: List[list]       # 内层不够精确

# 使用 Optional 处理默认 None
from typing import Optional
def get_items() -> Optional[List[int]]:
    return None

要点总结

  • List[T] 注解列表元素类型
  • Dict[K, V] 注解字典键值类型
  • Tuple[T1, T2] 注解固定长度元组
  • Tuple[T, ...] 注解可变长度元组
  • Set[T] 注解集合元素类型
  • 支持多层嵌套复合类型
  • Python 3.9+ 可用小写内置类型
  • 精确注解元素类型优于泛型注解
  • 复合类型注解精确描述数据结构

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 基本类型注解
下一篇 → Python 类型别名
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库