1. list(列表)

列表就是 Python 最常用的数据结构,相当于 C++ 的 vector。
创建
nums = [3, 1, 2]
获取长度
len(nums)
返回
3
访问元素
nums[0] # 第一个
nums[-1] # 最后一个
Python 支持负数索引:
nums = [3,1,2]
0 1 2
-3 -2 -1
添加元素
尾部添加(O(1))
nums.append(5)
结果
[3,1,2,5]
指定位置插入
nums.insert(1,100)
结果
[3,100,1,2]
时间复杂度 O(n)
删除元素
删除最后一个
nums.pop()
返回删除的值
x = nums.pop()
例如
nums=[3,1,2]
x=nums.pop()
print(x)
输出
2
删除指定位置
nums.pop(1)
删除指定值
nums.remove(2)
如果不存在会报错。
排序
原地排序
nums.sort()
降序
nums.sort(reverse=True)
返回新的排序结果
sorted(nums)
例如
nums=[3,2,1]
new_nums=sorted(nums)
print(nums)
print(new_nums)
输出
[3,2,1]
[1,2,3]
区别:
sort() 修改原数组
sorted() 返回新数组
这是 LeetCode 经常考的。
翻转
nums.reverse()
或者
nums[::-1]
推荐:
nums[::-1]
不会修改原数组。
求和
sum(nums)
最大最小
max(nums)
min(nums)
2. String(字符串)
字符串不能修改。
例如
s="hello"
不能写
s[0]='a'
会报错。
长度
len(s)
索引
s[0]
切片
s[1:4]
结果
ell
规则:
左闭右开
即
1<=index<4
翻转字符串
s[::-1]
这是 LeetCode 高频。
排序
sorted(s)
返回
['e','h','l','l','o']
如果需要字符串
"".join(sorted(s))
得到
ehllo
这就是 Group Anagrams 的核心。
split
字符串切割
s="a,b,c"
s.split(",")
得到
['a','b','c']
join
拼接
arr=['a','b','c']
"".join(arr)
得到
abc
3. Dictionary(字典)


刷题最重要的数据结构。
相当于 C++ unordered_map。
创建
d={}
添加
d["a"]=10
修改
d["a"]=20
查询
d["a"]
如果不存在
会报错。
推荐
d.get("a")
不存在返回
None
或者
d.get("a",0)
不存在返回
0
判断是否存在
if "a" in d:
不要写
if d["a"]:
容易报错。
遍历
for key,value in d.items():
例如
{
"a":1,
"b":2
}
输出
a 1
b 2
4. Set(集合)

特点:
没有重复元素。
创建
s=set()
添加
s.add(3)
删除
s.remove(3)
判断
if 3 in s:
复杂度 O(1)
去重
nums=list(set(nums))
例如
[1,1,2,3]
变成
[1,2,3]
注意:
顺序可能改变。
5. Counter
统计频率神器。
from collections import Counter
例如
nums=[1,2,2,2,3]
cnt=Counter(nums)
得到
{
2:3,
1:1,
3:1
}
查询
cnt[2]
得到
3
出现最多
cnt.most_common(2)
得到
[(2,3),(1,1)]
非常常见。
例如 Top K Frequent。
6. defaultdict
最推荐使用。
普通字典
d={}
需要
if key not in d:
d[key]=[]
defaultdict
from collections import defaultdict
d=defaultdict(list)
直接
d[key].append(x)
Group Anagrams 就可以写成
from collections import defaultdict
d=defaultdict(list)
for word in strs:
key="".join(sorted(word))
d[key].append(word)
7. enumerate
以前
for i in range(len(nums)):
推荐
for i,x in enumerate(nums):
例如
nums=[3,5,8]
得到
i=0 x=3
i=1 x=5
i=2 x=8
更 Pythonic。
8. zip
两个数组一起遍历。
A=[1,2]
B=[3,4]
for x,y in zip(A,B):
print(x,y)
输出
1 3
2 4
矩阵转置也经常用:
matrix = [
[1,2,3],
[4,5,6]
]
print(list(zip(*matrix)))
输出:
[(1,4), (2,5), (3,6)]
* 表示解包,把二维列表的每一行作为参数传给 zip。
9. 排序
最重要。
普通
nums.sort()
二维数组
points.sort(key=lambda x:x[0])
按第二列
points.sort(key=lambda x:x[1])
先按第一列再按第二列
points.sort(key=lambda x:(x[0],x[1]))
例如
[[2,3],
[1,5],
[2,1]]
排序后
[[1,5],
[2,1],
[2,3]]
10. heapq
Python 默认只有最小堆。
import heapq
加入
heapq.heappush(heap,3)
弹最小
heapq.heappop(heap)
如果想实现最大堆,可以存负数:
heap = []
heapq.heappush(heap, -5)
heapq.heappush(heap, -2)
print(-heapq.heappop(heap)) # 5
11. deque
双端队列。
from collections import deque
q=deque()
队尾
q.append(3)
队首
q.appendleft(5)
左边弹
q.popleft()
右边弹
q.pop()
BFS、滑动窗口都会用。
12. 二维数组初始化
很多新手会写:
grid = [[0] * 3] * 3
看似得到:
[
[0,0,0],
[0,0,0],
[0,0,0]
]
但实际上三行引用的是同一个列表。
验证:
grid = [[0] * 3] * 3
grid[0][0] = 1
print(grid)
输出:
[
[1,0,0],
[1,0,0],
[1,0,0]
]
三行都变了。
正确写法:
grid = [[0] * 3 for _ in range(3)]
这样每一行都是独立的列表。
背熟的 API
| API | 用途 | 高频题型 |
|---|---|---|
append() |
列表尾部添加 | 几乎所有题 |
pop() / popleft() |
栈、队列 | DFS、BFS |
sort() / sorted() |
排序 | 排序、贪心 |
enumerate() |
下标 + 元素遍历 | 数组 |
zip() |
多数组遍历、矩阵转置 | 矩阵、字符串 |
Counter() |
统计频率 | 哈希、Top K |
defaultdict(list) |
分组 | Group Anagrams、图 |
set() |
去重、快速查找 | 哈希 |
heapq |
优先队列 | Top K、合并 K 个链表 |
deque |
双端队列 | BFS、滑动窗口 |
"".join() / split() |
字符串拼接与切割 | 字符串 |
tuple() |
构造可哈希键 | 哈希分组 |
时间复杂度
