四大容器,四种性格
languages = ['Python', 'JavaScript', 'Go'] # list:有序、可变
point = (31.23, 121.47) # tuple:有序、不可变
user = {'name': '小明', 'level': 3} # dict:键值对
tags = {'python', ' beginner', 'python'} # set:不重复
list:最常用的容器
todo = ['学 Python', '写笔记']
todo.append('部署网站') # 尾部添加
todo.pop() # 尾部取出
todo[0] # '学 Python'(下标从 0 开始)
todo[::-1] # 反转切片
len(todo) # 长度
dict:按键取值,快到 O(1)
scores = {'语文': 92, '数学': 88}
scores['英语'] = 95 # 新增
scores['数学'] # 88 —— 无论字典多大,查找都是瞬间
scores.get('物理', 0) # 安全取值,不存在返回默认值 0
for subject, score in scores.items():
print(f'{subject}: {score}')
需要「按编号查名字」「按 ID 查配置」这类映射关系时,第一反应就该是 dict。
set:去重与集合运算
learned = {'python', 'html'}
roadmap = {'python', 'html', 'react', 'rust'}
learned & roadmap # 交集 {'python', 'html'}:已学且在路线内
roadmap - learned # 差集 {'react', 'rust'}:还没学的
推导式:Pythonic 的一行流
nums = [1, 2, 3, 4, 5]
squares = [n * n for n in nums if n % 2 == 1] # [1, 9, 25]
id2name = {i: f'同学{i}' for i in range(3)}
💡 选型口诀:有序可变用 list,固定不变用 tuple,按键查找用 dict,天然去重用 set。