前言
此系列笔记是拨珠自己的学习笔记,自用为主,学习建议移步其他大佬的专门教程。
math库
Python 的 math
库是标准库之一,提供了大量数学运算相关的函数,适用于基础数学计算、科学计算等场景。下面详细介绍其使用方法及常用功能:
1. 库的调用
math
是 Python 内置标准库,无需额外安装,直接通过 import
语句导入即可使用:
import math # 导入整个库
# 或只导入需要的函数(推荐,减少内存占用)
from math import ceil, floor, factorial, comb, pow, sqrt, gcd, sin, cos, log, exp
2. 常用功能及示例
(1)向上取整与向下取整
math.ceil(x)
:向上取整,返回大于等于x
的最小整数math.floor(x)
:向下取整,返回小于等于x
的最大整数
import mathprint(math.ceil(3.2)) # 输出:4
print(math.ceil(-2.8)) # 输出:-2(向上取整靠近0)
print(math.floor(3.8)) # 输出:3
print(math.floor(-2.1)) # 输出:-3(向下取整远离0)
(2)阶乘
math.factorial(n)
:返回非负整数n
的阶乘(n! = 1×2×...×n
),n=0
时返回 1
import mathprint(math.factorial(5)) # 输出:120(5! = 5×4×3×2×1)
print(math.factorial(0)) # 输出:1(0! 定义为1)
(3)组合数
math.comb(n, k)
:返回从n
个元素中选择k
个元素的组合数(C(n,k) = n!/(k!·(n-k)!)
),要求n ≥ k ≥ 0
import mathprint(math.comb(5, 2)) # 输出:10(从5个中选2个的组合数)
print(math.comb(10, 3)) # 输出:120
(4)指数与对数
math.exp(x)
:返回自然指数e^x
(e≈2.718
)math.log(x[, base])
:返回以base
为底x
的对数,默认底为e
(自然对数)math.log10(x)
:返回以 10 为底x
的对数(常用对数)
import mathprint(math.exp(1)) # 输出:2.71828...(e^1)
print(math.log(math.e)) # 输出:1.0(自然对数 ln(e))
print(math.log(8, 2)) # 输出:3.0(以2为底8的对数)
print(math.log10(100)) # 输出:2.0(lg(100))
(5)幂运算与开方
math.pow(x, y)
:返回x
的y
次幂(x^y
),与内置**
运算符类似,但返回浮点数math.sqrt(x)
:返回x
的平方根(√x
),要求x ≥ 0
import mathprint(math.pow(2, 3)) # 输出:8.0(2^3)
print(math.sqrt(25)) # 输出:5.0(√25)
print(math.sqrt(2)) # 输出:1.4142...(√2)
(6)最大公约数(GCD)
math.gcd(a, b)
:返回两个非负整数 a
和 b
的最大公约数,a
和 b
不能同时为 0
import mathprint(math.gcd(12, 18)) # 输出:6(12和18的最大公约数)
print(math.gcd(7, 5)) # 输出:1(7和5互质)
(7)三角函数
math
库的三角函数默认使用弧度制,需注意角度与弧度的转换(math.radians(x)
可将角度转为弧度):
- 正弦:
math.sin(x)
- 余弦:
math.cos(x)
- 正切:
math.tan(x)
- 反三角函数:
math.asin(x)
、math.acos(x)
、math.atan(x)
import math# 计算30度的正弦值(先转弧度)
angle = 30
radian = math.radians(angle)
print(math.sin(radian)) # 输出:0.5(sin(30°)=0.5)print(math.cos(math.pi)) # 输出:-1.0(cos(π) = -1)
collections库
counter:计数器
基本用法
(1)导入 Counter
from collections import Counter
(2)创建 Counter
对象
可以传入可迭代对象(如列表、元组、字符串等)来初始化:
# 统计列表中元素的出现次数
nums = [1, 2, 3, 2, 1, 3, 3, 4]
count = Counter(nums)
print(count) # 输出:Counter({3: 3, 1: 2, 2: 2, 4: 1})# 统计字符串中字符的出现次数
s = "hello world"
count_char = Counter(s)
print(count_char) # 输出:Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
(3)获取元素的计数
通过键访问,类似字典:
count = Counter([1, 2, 3, 2, 1, 3, 3, 4])
print(count[3]) # 输出:3(数字3出现了3次)
print(count[5]) # 输出:0(不存在的元素默认计数为0)
counter可以直接统计列表中元素出现的次数
回顾
输入一段文本(一组数据),统计每个字符出现次数
#读入文本
s = input()#统计数据
C = {}
for i in s:C[i] = C.get(i, 0) + 1#打印结果
for x, y in C.items():print("{} : {}".format(x, y))
常用函数
1. 设初值(初始化方式)
除了传入可迭代对象,Counter
还支持多种初始化方式:
空初始化:创建空的
Counter
,后续通过键值对添加from collections import Counter c = Counter() # 空Counter c['a'] = 2 c['b'] = 3 print(c) # Counter({'b': 3, 'a': 2})
字典初始化:通过键值对字典直接初始化
c = Counter({'a': 5, 'b': 2, 'c': 3}) print(c) # Counter({'a': 5, 'b': 2, 'c': 3})
关键字参数初始化:通过关键字参数指定计数
c = Counter(a=3, b=1, c=2) print(c) # Counter({'a': 3, 'c': 2, 'b': 1})
2. 核心方法详解
(1)most_common(k)
功能:返回包含前
k
个出现次数最多元素的列表,每个元素是(元素, 计数)
的元组。若
k
大于元素总数,返回所有元素;若k=None
,返回所有元素(按计数降序)。若多个元素计数相同,顺序不固定(取决于插入顺序)。
c = Counter('abracadabra') # 统计字符串中字符 print(c.most_common(3)) # 前3个最常见元素 # 输出:[('a', 5), ('b', 2), ('r', 2)]print(c.most_common()) # 所有元素按计数排序 # 输出:[('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]
(2)elements()
功能:返回一个迭代器,包含所有元素,每个元素重复的次数等于其计数(计数≤0 的元素会被忽略)。此方法可应用于把counter变回一个列表。
元素顺序与插入顺序一致,适合将计数结果还原为原始元素序列。
c = Counter(a=3, b=2, c=0, d=-1) elements = list(c.elements()) # 转换为列表 print(elements) # ['a', 'a', 'a', 'b', 'b'](忽略c和d,因计数≤0)
(3)clear()
功能:清空
Counter
中的所有元素和计数,使其变为空对象。c = Counter(a=2, b=3) c.clear() print(c) # Counter()(空对象)
3. 与字典类似的功能
Counter
是 dict
的子类,因此支持大多数字典的操作:
访问 / 修改计数:通过键直接操作,不存在的键默认计数为 0
c = Counter(a=2, b=3) print(c['a']) # 2(访问计数) c['a'] += 1 # 修改计数 print(c['a']) # 3 print(c['c']) # 0(不存在的键默认返回0)
获取键 / 值 / 键值对:
keys()
、values()
、items()
c = Counter(a=2, b=3) print(list(c.keys())) # ['a', 'b'] print(list(c.values())) # [2, 3] print(list(c.items())) # [('a', 2), ('b', 3)]
删除元素:
del
关键字c = Counter(a=2, b=3) del c['a'] # 删除键'a' print(c) # Counter({'b': 3})
检查键是否存在:
in
关键字c = Counter(a=2) print('a' in c) # True print('b' in c) # False
4. 数学运算
Counter
支持多种集合类数学运算,方便对两个计数结果进行合并、求差等操作(仅保留计数为正的元素):
加法(
+
):合并两个Counter
,相同元素的计数相加c1 = Counter(a=2, b=3) c2 = Counter(a=1, c=4) print(c1 + c2) # Counter({'c': 4, 'b': 3, 'a': 3})
减法(
-
):求差集,相同元素的计数相减(结果只保留计数 > 0 的元素)c1 = Counter(a=5, b=3) c2 = Counter(a=2, b=1, c=4) print(c1 - c2) # Counter({'a': 3, 'b': 2})(5-2=3,3-1=2,忽略c)
交集(
&
):取两个Counter
中相同元素的最小计数c1 = Counter(a=3, b=2, c=1) c2 = Counter(a=2, b=4, d=5) print(c1 & c2) # Counter({'a': 2, 'b': 2})(取a的min(3,2),b的min(2,4))
并集(
|
):取两个Counter
中相同元素的最大计数c1 = Counter(a=3, b=2, c=1) c2 = Counter(a=2, b=4, d=5) print(c1 | c2) # Counter({'b': 4, 'd': 5, 'a': 3, 'c': 1})(取a的max(3,2),b的max(2,4))
负数(
-c
):返回计数取负的Counter
(但通常结合其他运算使用)c = Counter(a=2, b=3) print(-c) # Counter({'a': -2, 'b': -3})
deque双端队列(与列表非常类似)
方法 / 属性 | 语法格式 | 功能描述 | 示例代码及输出 |
---|---|---|---|
clear() | deque.clear() | 清空双端队列中的所有元素,使其变为空队列(无返回值)。 | d = deque([1,2,3]); d.clear(); print(d) → deque([]) |
copy() | deque.copy() | 复制当前双端队列,返回一个浅拷贝(新队列与原队列元素相同,但修改新队列不影响原队列)。 | d = deque([1,2]); d2 = d.copy(); d2.append(3); print(d) → deque([1,2]) |
count(x) | deque.count(x) | 统计元素 x 在双端队列中出现的次数,返回整数。 | d = deque([1,2,2,3,2]); print(d.count(2)) → 3 |
index(x) | deque.index(x[, start[, end]]) | 返回元素 x 在队列中首次出现的索引(可指定搜索范围 [start, end) ),不存在则抛 ValueError 。 | d = deque([1,3,2,3]); print(d.index(3)) → 1 ;d.index(3, 2) → 3 |
reverse() | deque.reverse() | 原地反转双端队列中的元素顺序(无返回值)。 | d = deque([1,2,3,4]); d.reverse(); print(d) → deque([4,3,2,1]) |
rotate(n=1) | deque.rotate(n) | 向右旋转 n 步(n 为负数则向左旋转),旋转 1 步即最后一个元素移到开头。 | d = deque([1,2,3,4]); d.rotate(2); print(d) → deque([3,4,1,2]) |
maxlen | deque.maxlen | 属性,返回队列最大长度(初始化时指定,不可修改),未指定则为 None (可无限增长)。 | d = deque([1,2], maxlen=5); print(d.maxlen) → 5 |
关键特性补充:
maxlen
是初始化时的固定属性,例如deque([1,2], maxlen=3)
创建的队列最多容纳 3 个元素,新增元素时会自动移除另一端的旧元素。reverse()
和rotate()
均为原地操作,直接修改原队列,不会返回新队列。copy()
为浅拷贝,若队列中包含可变对象(如列表),修改拷贝队列中的可变对象会影响原队列。
defaultdict:有默认值的字典
即使一开始key不存在也不会报错
1. 基本用法
(1)导入 defaultdict
from collections import defaultdict
(2)创建 defaultdict
对象
需要指定一个默认值工厂函数(如 int
、list
、str
等),当访问不存在的键时,会自动调用该函数生成默认值。
# 示例1:默认值为0(用int作为工厂函数)
d = defaultdict(int)
d['a'] += 1 # 键'a'不存在时,自动初始化为0,再+1
print(d['a']) # 输出:1
print(d['b']) # 键'b'不存在,返回默认值0# 示例2:默认值为空列表(用list作为工厂函数)
d = defaultdict(list)
d[' fruits'].append('apple') # 键'fruits'自动初始化为空列表,再添加元素
print(d['fruits']) # 输出:['apple']
print(d['vegetables']) # 键不存在,返回空列表[]
2. 常用默认值类型
工厂函数 | 默认值 | 适用场景 |
---|---|---|
int | 0 | 计数统计(如统计元素出现次数) |
list | [] | 分组存储(如将元素按 key 分组到列表) |
dict | {} | 嵌套字典(如多层级键值存储) |
set | set() | 去重存储(如按 key 存储不重复元素) |
str | '' | 字符串拼接(如按 key 累积字符串) |
3. 与普通字典的区别
普通字典访问不存在的键会报错:
normal_dict = {} print(normal_dict['key']) # 抛出 KeyError: 'key'
defaultdict
会自动生成默认值:d = defaultdict(str) print(d['key']) # 输出空字符串 ''(无报错)
4. 典型应用场景
(1)统计元素出现次数
from collections import defaultdictwords = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
count = defaultdict(int) # 默认值0for word in words:count[word] += 1 # 直接累加,无需判断键是否存在print(dict(count)) # 转换为普通字典:{'apple': 3, 'banana': 2, 'orange': 1}
(2)按 key 分组元素
from collections import defaultdictpairs = [('fruit', 'apple'), ('vegetable', 'carrot'), ('fruit', 'banana')]
groups = defaultdict(list) # 默认值为空列表for key, value in pairs:groups[key].append(value) # 自动按key分组print(dict(groups)) # {'fruit': ['apple', 'banana'], 'vegetable': ['carrot']}
heapq堆
heapq
是 Python 标准库中用于实现堆(heap) 操作的模块,主要提供了基于最小堆的一系列功能,可用于实现优先级队列等场景。堆是一种特殊的完全二叉树,其中最小堆的父节点值始终小于等于子节点值。
上面的叫父亲节点,左边的叫左儿子,右边的叫右儿子,二叉树一个节点最多有两叉,而且一定要两个儿子都填满才会往下填。
1. 基本用法
(1)导入模块
import heapq
(2)核心操作
创建堆:通过
heapq.heapify(list)
将列表原地转换为最小堆(时间复杂度 O (n))。nums = [3, 1, 4, 2] heapq.heapify(nums) # 转换为最小堆 print(nums) # 输出:[1, 2, 4, 3](堆的内部存储结构)
添加元素:
heapq.heappush(heap, item)
向堆中添加元素,并维持堆结构。heap = [] heapq.heappush(heap, 3) heapq.heappush(heap, 1) heapq.heappush(heap, 2) print(heap) # 输出:[1, 3, 2](始终保持最小元素在堆顶)
弹出最小元素:
heapq.heappop(heap)
移除并返回堆中最小的元素(堆顶),自动调整堆结构。print(heapq.heappop(heap)) # 输出:1 print(heap) # 输出:[2, 3](剩余元素重新构成最小堆)
2. 常用功能
获取最小元素(不弹出):直接访问堆的第一个元素
heap[0]
。print(heap[0]) # 输出:2(当前堆顶元素)
合并多个有序序列:
heapq.merge(*iterables)
合并多个有序迭代器,返回一个生成器(需手动转换为列表)。list1 = [1, 3, 5] list2 = [2, 4, 6] merged = heapq.merge(list1, list2) print(list(merged)) # 输出:[1, 2, 3, 4, 5, 6]
获取前 n 个最大 / 小元素:
heapq.nlargest(n, iterable)
:返回迭代器中最大的 n 个元素。heapq.nsmallest(n, iterable)
:返回迭代器中最小的 n 个元素。
nums = [5, 2, 9, 1, 5, 6] print(heapq.nlargest(3, nums)) # 输出:[9, 6, 5] print(heapq.nsmallest(3, nums)) # 输出:[1, 2, 5]
堆其实就是一个特殊的列表,它最常用的功能就是找到列表中的最小值。
functool函数工具中的partial
functools.partial
是 Python 中 functools
模块提供的一个实用工具,用于固定函数的部分参数,生成一个新的简化版函数(偏函数)。它可以减少函数调用时需要传入的参数数量,提高代码复用性。
1. 基本用法
(1)导入 partial
from functools import partial
(2)核心功能:固定参数
假设有一个需要多个参数的函数,使用 partial
可以固定其中一部分参数,生成一个只需传入剩余参数的新函数。
def multiply(x, y):return x * y# 固定第一个参数 x=2,生成新函数 double
double = partial(multiply, 2)
print(double(3)) # 等价于 multiply(2, 3) → 输出 6
print(double(5)) # 等价于 multiply(2, 5) → 输出 10# 固定第二个参数 y=3,生成新函数 triple
triple = partial(multiply, y=3)
print(triple(4)) # 等价于 multiply(4, 3) → 输出 12
2. 适用场景
简化重复调用:当函数需要频繁以相同参数调用时,用
partial
固定重复参数,减少代码冗余。import requests from functools import partial# 固定请求方法为 GET,生成简化的 get 请求函数 get = partial(requests.request, 'GET') # 调用时只需传入 URL response = get('https://www.example.com')
适配函数参数:当需要将一个多参数函数作为回调函数(通常要求参数更少)时,用
partial
适配参数数量。from functools import partialdef greet(greeting, name):print(f"{greeting}, {name}!")# 固定 greeting="Hello",生成适配单参数的回调函数 hello_greet = partial(greet, "Hello") # 回调场景中只需传入 name names = ["Alice", "Bob"] for name in names:hello_greet(name) # 输出:Hello, Alice! / Hello, Bob!
位置固定:按原函数参数顺序固定值(不写参数名),新参数自动补在后面。
例:def add(x,y,z): return x+y+z
add10 = partial(add, 10)
→ 固定x=10
,调用add10(2,3)
等价于add(10,2,3)
。参数固定:用
参数名=值
固定特定参数(不依赖顺序),新参数传未固定的部分。
例:add_y20 = partial(add, y=20)
→ 固定y=20
,调用add_y20(1,3)
等价于add(1,20,3)
。
3. 关键特性
partial
生成的新函数可以像原函数一样被调用,且支持传入额外参数(会补充在固定参数之后)。- 若固定参数时指定了关键字参数(如
partial(func, y=3)
),调用新函数时不能再用位置参数重复传入,避免冲突。
intertools迭代器工具
itertools
是 Python 用于高效循环的工具库,提供了三类常用迭代器:
1. 无限迭代器
可无限生成元素,需手动终止(如用 break
),常用 3 个:
迭代器 | 功能 | 示例 |
---|---|---|
count(start, step) | 从 start 开始,按 step 递增 | count(2, 2) → 2,4,6,8... |
cycle(iterable) | 循环重复可迭代对象中的元素 | cycle([1,2]) → 1,2,1,2... |
repeat(val, n) | 重复 val ,n 为次数(缺省则无限) | repeat(3, 2) → 3,3 |
2. 有限迭代器
处理有限可迭代对象,返回新的迭代器,常用:
迭代器 | 功能 | 示例 |
---|---|---|
chain(*iterables) | 拼接多个可迭代对象 | chain([1,2], (3,4)) → 1,2,3,4 |
accumulate(iterable, func) | 累积计算(默认求和) |
|
accumulate在前缀和的使用中有大用
itertools.accumulate
是用于累积计算的迭代器,它对可迭代对象(如列表、元组)中的元素进行连续操作,返回每一步的累积结果,默认是累加,也可自定义运算逻辑。
基本用法
1. 语法
itertools.accumulate(iterable, func=None)
iterable
:需要处理的可迭代对象(如列表、range 等)func
:可选参数,指定累积运算的函数(默认是operator.add
,即加法)
2. 默认行为(累加)
不指定 func
时,默认对元素依次求和:
from itertools import accumulatenums = [1, 2, 3, 4]
result = accumulate(nums)
print(list(result)) # 输出:[1, 3, 6, 10]
# 计算过程:1 → 1+2=3 → 3+3=6 → 6+4=10
3. 自定义运算(通过 func
参数)
指定 func
可以实现其他累积逻辑(如乘法、最大值等):
from itertools import accumulate
import operator# 累乘(用 operator.mul)
nums = [1, 2, 3, 4]
product = accumulate(nums, func=operator.mul)
print(list(product)) # 输出:[1, 2, 6, 24]
# 计算过程:1 → 1×2=2 → 2×3=6 → 6×4=24# 累积取最大值(用 max 函数)
nums = [3, 1, 4, 2]
max_accum = accumulate(nums, func=max)
print(list(max_accum)) # 输出:[3, 3, 4, 4]
# 计算过程:3 → max(3,1)=3 → max(3,4)=4 → max(4,2)=4
4. 处理非数字类型
只要 func
支持对应类型的运算,也可处理其他数据(如字符串拼接):
from itertools import accumulatewords = ["a", "b", "c"]
str_accum = accumulate(words, func=lambda x, y: x + y)
print(list(str_accum)) # 输出:['a', 'ab', 'abc']
关键特点
惰性计算:只在需要时生成结果,节省内存(尤其适合大数据)。
长度不变:返回的迭代器长度与原可迭代对象一致(第
i
个元素是前i+1
个元素的累积结果)。依赖顺序:累积结果与元素顺序相关(如
[1,2]
和[2,1]
的累加结果不同)。
accumulate
非常适合需要 “逐步记录中间结果” 的场景,如累计求和、累计乘积、历史最大值追踪等,避免手动写循环累加的冗余代码。
3. 排列组合迭代器
生成元素的排列或组合,适用于数学计算:
迭代器 | 功能 | 示例 |
---|---|---|
product(*iterables, repeat=1) | 笛卡尔积(元素组合) | product([1,2], ['a']) → (1,'a'),(2,'a') |
permutations(iterable, r) | 从 iterable 选 r 个元素的排列(有序) | permutations([1,2,3], 2) → (1,2),(1,3),(2,1)... |
combinations(iterable, r) | 从 iterable 选 r 个元素的组合(无序) | combinations([1,2,3], 2) → (1,2),(1,3),(2,3) |
combinations_with_replacement(iterable, r) | 允许重复元素的组合 | combinations_with_replacement([1,2], 2) → (1,1),(1,2),(2,2) |