for |
range |
和len结合使用相当于取某范围List下标,第三个参数为步长 |
N/A |
N/A |
for i in range(len(nums))前闭后开,用逗号 |
for |
in |
枚举列表的每个数 |
N/A |
N/A |
for n in nums |
for |
range |
逆序遍历 |
N/A |
N/A |
for i in range(len(nums) - 1, -1, -1)前闭后开, 或用reversed(range(len(nums))) |
for |
enumerate |
枚举List的下标和数值,与range不同的是它不能指定范围和步长 |
N/A |
N/A |
for i, n in enumerate(nums) |
Math |
max/min |
取最大值 |
Num |
Num |
max_len = max(2, 3) 或min(1, 2, 3) |
Math |
pow |
求幂值 |
Num |
Num |
val = pow(2, 3) |
Math |
int |
str转int或将float变成int |
String |
Num |
val = int(‘123’), val = int(2.6) -> 2 |
Math |
math.ceil/floor |
求向上或下取整 |
Num |
Num |
import math, val = math.ceil(5/2), math.floor(5/2) |
Math |
float(‘inf’) |
无穷大值 |
N/A |
Num |
val = float(‘inf’) or float(‘-inf’) |
Math |
min |
求数组中的正数的最小值 |
N/A |
Num |
min(n for n in nums if n > 0) |
Math |
len |
求数组中的正数的个数 |
N/A |
Num |
len([n for n in nums if n > 0]) |
Math |
sum |
求数组和 |
N/A |
Num |
sum(nums) |
Math |
abs |
求绝对值 |
Num |
Num |
abs(-1) |
Math |
//与int |
求整数值 |
Num |
Num |
//是比它小的整数如-2.8就是-3,只在负数是有区别。写程序用的更多是int(num / a)结果是-2,这和Java一致 |
String |
str |
任意类型变成字符串 |
Any |
String |
str(2) |
String |
replace |
替换 |
String |
String |
‘abc’.replace(‘c’, ‘d’) |
String |
format |
格式化字符串 |
Any |
String |
‘{} of {}’.format(a, b) |
String |
[] |
得到某一个字符 |
N/A |
Char |
s[2] |
String |
[] |
得到子串(前闭后开) |
N/A |
string |
s = ‘abc’, s[:2] -> ‘ab’, s[2:] -> ‘c’ |
String |
len |
得到字符串长度 |
N/A |
int |
num = len(s) |
String |
[::-1] |
反转字符串 |
N/A |
String |
new_str = s[::-1] |
String |
[:-1] |
(DFS中)去掉最后一个字符 |
N/A |
String |
path = path[:-1] |
String |
N/A |
两个字符串叉乘 |
N/A |
List |
a_list = [s + c for s in s1 for c in s2] |
String |
> |
比较两个字符串 |
N/A |
boolean |
‘111’ > ‘21’ -> False, ‘21’ == ‘21’ -> True |
String |
find |
查找返回下标 |
str |
str |
‘word’.find(‘w’) 若找不到返回-1 |
String |
upper |
变成全部大写 |
str |
str |
‘word’.upper() |
String |
lower |
变成全部大写 |
str |
str |
‘WORD’.lower() |
String |
startswith |
是否以某个字母开头 |
str |
Boolean |
‘word’.startswith(‘w’) |
String |
endswith |
是否以某个字母结尾 |
str |
Boolean |
‘word’.endswith(‘d’) |
String |
strip, lstrip, rstrip |
去掉空格 |
N/A |
str |
‘word ‘.strip(), ‘word ‘.lstrip(), ‘word ‘.rstrip() |
String |
split |
用分隔符变成List |
str |
List |
‘a,b’.split(‘,’) |
String |
+ |
一个个字符加到字符串末 |
N/A |
N/A |
res += ‘g’ |
String |
in |
查看某个字符是否属于一个字符集合里 |
N/A |
bool |
if char in ‘([{‘ 可以避免用list |
String |
isalpha |
是否字母 |
N/A |
bool |
‘ab’.isalpha() |
String |
isdigit |
是否数字 |
N/A |
bool |
‘23’.isdigit() |
String |
ascii_lowercase |
a-z的所有字母 |
str |
str |
import string, string.ascii_lowercase |
String |
ord |
一个字母的ASCII |
str |
str |
ord(‘A’) = 65 |
String |
eval |
计算字符串的数值,变量,函数运算结果,返回数字 |
str |
Num |
eval(‘5+ 6’) = 11, num = 1, eval(num + 1) = 2, eval(‘f(2)’) |
String |
ljust |
靠左右边补空格 |
str |
str |
line.ljust(maxWidth), line.ljust(maxWidth, ‘#’) |
List |
[] |
初始化列表 |
N/A |
N/A |
li = [],这是空列表,不能通过索引取值 |
List |
[] |
初始化固定大小的列表 |
N/A |
N/A |
li = [0] * 10, [None] * 10 -> 创建一个list, * 是复制只能用于标量,若矢量是复制ref如[[]] * 10, 要用[[] for _ in range(10)] |
List |
len |
大小 |
N/A |
int |
num = len(li) |
List |
append |
尾部加入 |
Any |
N/A |
li.append(‘apple’) |
List |
insert |
头部加入 |
Any |
N/A |
li.insert(0, ‘apple’) |
List |
pop |
头部/某位置删除 |
Any |
N/A |
li.pop(0), li.pop(2) |
List |
remove |
按值删除 |
Any |
N/A |
li.remove(3) |
List |
+ |
两个list合并 |
N/A |
N/A |
list1 + list2 |
List |
extend |
两个list合并到第一个 |
Any |
N/A |
li.extend([‘apple’, ‘banana’]) |
List |
join |
加入分隔符 |
List |
String |
‘,’.join(li), 将字符列表变成字符串’’.join(char_list) |
List |
sort |
原地排序,如果List的元素是tuple,按第一个元素排序 |
List |
N/A |
li.sort(), 如果不改变原数组用list(li)先复制 |
List |
sort |
按字符串长度降序排列 |
List |
N/A |
words.sort(key=len, reverse=True), intervals.sort(key=lambda x: x[0]), 按两个key来排序li.sort(key=lambda x: (x[0], x[1]))先顺序再逆序li.sort(key=lambda x: (x[0], -x[1])) |
List |
sorted |
非原地排序 |
List |
N/A |
nums[idx+1:] = sorted(nums[idx+1:]) |
List |
list |
复制list |
List |
List |
new_list = list(old_list) |
List |
list |
扩展一倍一样的list |
List |
List |
new_list = nums * 2 |
List |
[] |
反转list |
List |
List |
new_list = li[::-1]跟反转string一样,反转子列表nums[idx+1:] = nums[len(nums)-1:idx:-1] |
List |
[-1] |
返回list中最后一个元素 |
T |
int |
li[-1],而不是dp[len(li)-1]广泛用于DP题 |
List |
index |
list中找某个元素 |
T |
int |
li.index(2), 找不到的话抛出异常,先要检查if 9 in li2 else -1. 字符串用find |
List |
count |
list中计算某个元素值的个数 |
T |
int |
li.count(‘a’) |
List |
[:] |
批量替换成list中某些元素 |
N/A |
N/A |
nums[start:end + 1] = res |
List |
[::-1] |
reverse sublist |
N/A |
N/A |
nums[:k] = nums[:k][::-1]先取sublist再倒转 |
deque |
deque |
初始化队列 |
N/A |
N/A |
from collections import deque, queue = deque(), queue = deque([node]) |
deque |
append |
入列 |
T |
N/A |
queue.append(node) |
deque |
popleft |
出列 |
Num |
T |
s = queue.popleft() |
deque |
appendleft |
队首入列 |
Num |
T |
s = queue.appendleft()较少用 |
deque |
[0] |
看列首元素 |
N/A |
T |
queue = [], s = queue[0] |
List(Heap) |
heapify |
对list最小堆排序 |
List |
N/A |
from heapq import heapify, pq = [2, 3], heapify(pq) 若最大堆,则将所有值取负加入堆 |
List(Heap) |
heappush |
入堆 |
List, T |
N/A |
from heapq import heappush, heappush(pq, 4) |
List(Heap) |
heappop |
出堆 |
List |
T |
from heapq import heappop, heappop(pq) |
List(Heap) |
heapreplace |
置换堆 |
T |
N/A |
heapq.heapreplace(pq, 4)= heappush(pq, 4) + heappop(pq) |
List(Heap) |
[0] |
看堆顶元素 |
N/A |
T |
pq[0] |
List(Stack) |
append |
入栈 |
T |
N/A |
stack = [], stack.append(node) |
List(Stack) |
pop |
出栈 |
N/A |
T |
stack = [], s = stack.pop() |
List(Stack) |
[] |
看栈顶元素 |
N/A |
T |
stack = [], s = stack[-1] |
Dictionary |
{} |
初始化字典 |
N/A |
N/A |
di = {}, di = {1: ‘a’, 2: ‘b’} |
Dictionary |
{} |
初始化字典带初始key |
N/A |
N/A |
di = collections.defaultdict(int), defaultdict(list)避免第一次赋值时需要写if语句,一定用。只有用下标di[2]才会产生key和value,其他2 in di, di.keys()都不会产生key. collections.defaultdict(lambda: [0, 0])用于value是pair, 默认返回1: collections.defaultdict(lambda: 1) |
Dictionary |
[] |
获得字典的值 |
T |
T |
di[key] |
Dictionary |
[] |
插入到字典 |
T |
T |
di[key] = 2 |
Dictionary |
items |
Dict的所有pairs |
N/A |
K,V |
for k, v in di.items() |
Dictionary |
items |
Dict的所有keys |
N/A |
List |
for k in di.keys(), 类型不是List,若要,则list(di.keys()) |
Dictionary |
in |
是否含有某个key |
N/A |
boolean |
if key in di |
Dictionary |
pop |
删除某个key |
N/A |
N/A |
di.pop(key) |
Set |
{} |
产生一个Set |
N/A |
Set |
b = set(), b = set([‘a’, ‘b’]) |
Set |
add |
set增加一个元素 |
T |
N/A |
b.add(‘c’) |
Set |
remove |
set删除一个元素 |
T |
N/A |
b.remove(‘c’) |
Set |
set |
List转换成Set或反之 |
N/A |
N/A |
s = set(l), l = list(s) |
bisect |
bisect |
二分法查找下标插入位置 |
Num |
Num |
跟greater_position一样, from bisect import bisect, bisect([], 3) -> 0, bisect([2], 3) -> 1, bisect([3], 3) -> 1, bisect([4], 3) -> 0。还可以用于统计小于等于target的个数,如bisect([0, 1], 1) -> 2 |
bisect |
bisect_left |
二分法查找下标插入位置 |
Num |
Num |
似于greater_or_equal_position但若equal时,取第一个,但greater_or_equal_position是取最后一个. 用于LIS |
bisect |
insort |
二分法查找下标插入位置且插入 |
Num |
Num |
似于greater_position,插入复杂度为O(n) |
bisect |
bisect |
二分法查找二维数组 |
Num |
Num |
bisect.bisect([[0, 1], [0, 2], [1, 2], [1, 3]], [1]) -> [1, 2]下标,若找[1, 2] -> [1, 3]下标 |
Lambda |
func/expr…for…in |
整型数组变字符串数组 |
List |
List |
[str(x) for x in list] |
Others |
return |
返回tuple值 |
N/A |
N/A |
return a, b 不要括号 |
Others |
isinstance |
判断输入是什么类型 |
N/A |
bool |
isinstance(stack[2], list) |
Others |
Counter |
计算List和字符串频率 |
List |
dict |
from collections import Counter, di = Counter(nums), di = Counter(‘apple’), graph = Counter({c: [] for word in words for c in word}) |
Others |
[] |
初始化NxM矩阵为0 |
N/A |
N/A |
a = [[1] * M] * N不能复制矢量。[[0 for _ in range(M)] for _ in range(N)] 先col再row |
Others |
randint |
求[start, end]之间随机值 |
Num |
Num |
import random, random.randint(0, 1) -> 0/1 |
Others |
map, max |
求矩阵最大值 |
[][] |
T |
max(map(max, matrix)) |
Others |
or |
若0返回1 |
N/A |
N/A |
a or 1 -> a if a != 0, 1 if a == 0 |
Others |
or |
若None返回[] |
N/A |
N/A |
for child in root.children or [] |
OrderedDict |
OrderedDict |
类似于LinkedHashMap,dict的key的插入顺序排序 |
N/A |
N/A |
di = collections.OrderedDict(), di[‘a’] = 2 |
re |
search |
search只match一次 |
str |
str |
re.search(r’(\+|\-)?\d+’, ‘-23.1e2’).group() -> -23 |
re |
sub |
全部用regex替代类似Java中的replaceAll |
str |
str |
re.sub(r’\s+’, ‘’, ‘a 6 7’) -> a67 |
Exception |
Exception |
抛出异常 |
N/A |
N/A |
raise Exception(‘abc’) |