python-base

大概2023年做的笔记

当年学python的笔记,放出来当速查表,查缺补漏比较合适

未填坑完毕

概述

线

基础语法

关键字

以python3.10为例,35个关键字

and as assert async await break class continue
def del elif else except False finally for
from global if import in is lambda None
nonlocal not or pass raise return True try
while with yield

查看所有的关键字:

1
2
import keyword
keyword.kwlist

生成关键字html表格:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import keyword
a=keyword.kwlist
a.sort(key=str.lower)
i=1
r=8
for s in a:
if i%r==1:
print('\t<tr>')
print('\t\t<td>'+s+r'</td>')
if i%r==0:
print('\t</tr>')
i+=1
if i%r!=1:
print('\t</tr>')
print(len(a))

常量与变量

python不定义常量,一般用大写字母表示常量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
修改一个变量的值,内存地址会发生变化

## 数据类型
$数据类型\begin{cases}
\textbf{数字类型}
\begin{cases}
\text{整数 } \mathtt{int}
\begin{cases}
\text{十进制: } 10,\ -5 \\
\text{二进制: } \mathtt{0b1010}\ (10) \\
\text{八进制: } \mathtt{0o12}\ (10) \\
\text{十六进制: } \mathtt{0xA},\ \mathtt{0Xa}\ (10)
\end{cases} \\
\\
\text{浮点数 } \mathtt{float}
\begin{cases}
\text{常规: } 3.14,\ -0.001 \\
\text{科学计数法: } \mathtt{1.3e4}\ (13000),\ \mathtt{-0.35e3}\ (-350),\ \mathtt{2.36e-3}\ (0.00236)
\end{cases} \\
\\
\text{布尔类型 } \mathtt{bool}
\begin{cases}
\mathtt{True}\ (\text{等价于 } 1) \\
\mathtt{False}\ (\text{等价于 } 0)
\end{cases} \\
\\
\text{复数 } \mathtt{complex}
\begin{cases}
\mathtt{1+2j} \\
\mathtt{complex(1,\ 2)}
\end{cases}
\end{cases} \\
\\
\textbf{序列类型}
\begin{cases}
\text{字符串 } \mathtt{str}:\ \text{"hello"},\ \text{'Python'} \\
\text{列表 } \mathtt{list}:\ [1,\ "a",\ True] \\
\text{元组 } \mathtt{tuple}:\ (1,\ "b",\ False)
\end{cases} \\
\\
\textbf{集合类型}
\begin{cases}
\text{集合 } \mathtt{set}:\ \{1,\ 2,\ 3\} \\
\text{冻结集合 } \mathtt{frozenset}:\ \mathtt{frozenset(\{1,\ 2\})}
\end{cases} \\
\\
\textbf{映射类型}
\begin{cases}
\text{字典 } \mathtt{dict}:\ \{"name":\ "Alice",\ "age":\ 25\}
\end{cases} \\
\\
\textbf{特殊类型}
\begin{cases}
\mathtt{NoneType}:\ \mathtt{None} \\
\mathtt{range}:\ \mathtt{range(5)}\ (0,\ 1,\ 2,\ 3,\ 4) \\
\mathtt{bytes}:\ \mathtt{b'data'}
\end{cases}
\end{cases} \\
\\
\textbf{数据类型转换}
\begin{cases}
\mathtt{int(x)} & \text{(浮点/布尔/合规字符串→整数)} \\
\mathtt{float(x)} & \text{(整数/布尔/合规字符串→浮点)} \\
\mathtt{str(x)} & \text{(任意类型→字符串)} \\
\mathtt{list(x)} & \text{(元组/集合→列表)} \\
\mathtt{tuple(x)} & \text{(列表/集合→元组)} \\
\\
\text{ASCII转换}
\begin{cases}
\mathtt{chr(x)}:\ \text{整数 } x \text{ → 字符(如 } \mathtt{chr(65)}\to"A\text{”)} \\
\mathtt{ord(x)}:\ \text{字符 } x \text{ → 整数值(如 } \mathtt{ord('A')}\to65\text{)}
\end{cases} \\
\\
\textbf{隐式转换}
\begin{cases}
\text{整数+浮点→浮点: } \mathtt{10\ +\ 3.14\ =\ 13.14} \\
\text{布尔+整数→整数: } \mathtt{True\ +\ 2\ =\ 3}
\end{cases}
\end{cases} \\
\\
\textbf{转换注意事项}
\begin{cases}
\text{浮点→整数: 截断小数(非四舍五入)} \\
\text{字符串→数字: 需格式合规(如 } \mathtt{int("123")\ \checkmark},\ \mathtt{int("12a")\ \times}\text{)} \\
\text{容器互转: 字典需用 } \mathtt{.keys()},\ \mathtt{.values()}\text{ 单独转换键/值}
\end{cases}
$
## 输入

```python
a=input()
mylist=input().split()# 以空格为分割输入列表
mylist=eval(input())
mylist=list(map(int,input.split())) # 以空格为分割输入整型列表
n,m=map(int,input.split())
n,m=map(int,input.split(',')) # 以逗号为分割

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
```eval```具有风险,可以利用执行系统命令、删除文件等操作

## 格式化输出
这一块当年记的不清楚,让ai写了
1. **`%` 格式化(传统方法)**
- **语法**:`"格式字符串" % (变量1, 变量2)`
- **常用格式符**:
- `%s`:字符串
- `%d`:十进制整数
- `%f`:浮点数(`%.2f` 保留两位小数)
- `%x`:十六进制整数
- **示例**:
```python
name = "Alice"
age = 25
print("Name: %s, Age: %d" % (name, age)) # 输出:Name: Alice, Age: 25
  • 适用场景:兼容旧代码(Python 2/3)或简单插值。
  1. str.format() 方法(灵活通用)

    • 语法"{} {}".format(var1, var2)
    • 核心功能
      • 位置参数{0}{1}
      • 关键字参数{name}{age}
      • 格式控制
        • 数字精度:{:.2f}
        • 千位分隔:{:,}
        • 对齐填充:{:<10}(左对齐)、{:>10}(右对齐)
    • 示例
      1
      2
      print("Name: {0}, Age: {1}, Salary: {2:,.2f}".format("Bob", 30, 12345.67))
      # 输出:Name: Bob, Age: 30, Salary: 12,345.67
    • 优势:支持复杂格式(如嵌套字典)。
  2. f-string(Python 3.6+ 推荐)

    • 语法f"{变量} {表达式}"
    • 核心特性
      • 直接嵌入变量与表达式:f"Sum: {a + b}"
      • 支持所有 str.format() 格式规范:{height:.2f}
      • 高性能(比前两种快 2-3 倍)
    • 示例
      1
      2
      3
      4
      name = "Charlie"
      height = 1.85
      print(f"Name: {name.upper()}, Height: {height:.1f}m")
      # 输出:Name: CHARLIE, Height: 1.9m
    • 适用场景:现代 Python 项目首选。

格式化

需求 语法示例 说明
数字精度控制 f"{pi:.3f}""{:.3f}".format(3.14159) 保留 3 位小数 → 3.142
千位分隔符 f"{salary:,}" 12345671,234,567
科学计数法 "{:.2e}".format(123456) 输出 1.23e+05
进制转换 "二进制: {num:b}".format(num=10) 输出 二进制: 1010
字符串对齐与填充 "{:*^10}".format("Hi") 居中填充 ****Hi****
日期格式化 f"{datetime.now():%Y-%m-%d}" 输出 2025-06-02

方法对比与选型建议

特性 % 格式化 str.format() f-string
语法简洁性 ★★☆ ★★★ ★★★★★
功能灵活性 ★★☆(仅基础类型) ★★★★★(支持复杂结构) ★★★★★(支持表达式)
性能 ★★★☆ ★★☆ ★★★★★(最快)
版本兼容性 Python 2+ Python 2.6+ Python 3.6+
推荐场景 旧代码维护 需复杂格式控制 新项目首选
  • 优先使用 f-string(简洁高效);
  • 需兼容旧版本时用 str.format()
  • 避免在循环中使用 + 拼接字符串(性能低下)。

运算符

除法:

  • /:除法。和c语言不同,整数/整数会获得小数
  • //:取整的除
  • %:取模
    1
    2
    3
    11/4=2.75
    11//4=2
    11%4=3
    优先级:从高到低
    ()
    **(求幂)
    + -(正负号)
    * / // %
    + -
    == != > >= < <=
    not
    and
    or

分支循环

当年没记,让AI替写一下这部分

🔀分支

  1. 单分支(if
  2. 双分支(if-else
  3. 多分支(if-elif-else
  4. 嵌套分支
  5. 三元表达式
    1
    result = value_if_true if condition else value_if_false

🔁 循环结构

  1. for循环
    遍历序列(列表、字符串、字典等)或迭代器:

    1
    2
    for item in sequence:
    # 循环体

    示例:

    1
    2
    for char in "Python":
    print(char) # 输出每个字符
    • 结合range():控制循环次数
      1
      2
      for i in range(5):    # 0到4
      print(i)
  2. while循环
    条件为真时重复执行:

    1
    2
    while condition:
    # 循环体
  3. 循环控制关键字

    • break:立即终止当前循环
    • continue:跳过本次迭代,进入下一轮
  4. 循环的else子句
    循环正常结束(非break中断)时执行:

    1
    2
    3
    4
    for i in range(3):
    print(i)
    else:
    print("Loop completed") #
  5. 嵌套循环

序列

列表

元组

字典

集合

字符串

函数

python的函数参数和返回值可以自由选择,也可以注明是什么类型

函数说明、注释与标注

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
第一行语句选择地使用“文档字符串”docomentation strings
```__doc__```函数注释
```python
def doc_demo(p1:str,p2:str=" is my favorite!")->str:
"""
doc测试
:param p1:最喜欢的字符串
:param p2:接的句子
:return:结果字符串
"""
return p1+p2

print("函数文档:",doc_demo.__doc__)
print("函数注释:",doc_demo.__annotations__)
print('函数帮助')
help(doc_demo)
if __name__ == '__main__':
print(doc_demo("Python"))
print(doc_demo("Python"," is the best!"))

返回:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

函数文档:
doc测试
:param p1:最喜欢的字符串
:param p2:接的句子
:return:结果字符串

函数注释: {'p1': <class 'str'>, 'p2': <class 'str'>, 'return': <class 'str'>}
函数帮助
Help on function doc_demo in module __main__:

doc_demo(p1: str, p2: str = ' is my favorite!') -> str
doc测试
:param p1:最喜欢的字符串
:param p2:接的句子
:return:结果字符串

Python is my favorite!
Python is the best!

变量作用域

匿名函数

参数传递

参数类型

参数传递时的序列解包

if name == ‘main‘:

__name__
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
简单说,就是本文件执行的时候,```__name__```才等于```'__main__'```,```if```里才会执行;别的文件调用本文件时,```__name__```不等于```'__main__'```,所以```if```不会执行,本文件就成为了个函数包

用途:
+ 防止代码在导入时执行:当你```import xxx```时,不会执行``` if __name__ == '__main__':```里的代码
+ 测试代码
+ 命令行工具:在``` if __name__ == '__main__':```块中解析命令行参数并执行主要的程序逻辑。
+ 防止循环创建子进程

# 面向对象
# 异常捕获
# 断言
# with-as
# 文件操作
# Optional
Optional 类型提示用于标记函数的参数
# 自带库
## math
## heapq
代替c艹的`priority_queue`
## collections
> 建议优先掌握`Counter`、`defaultdict`和`deque`,覆盖90%的日常开发场景。

```mermaid
graph LR
A[collections模块] --> B[核心容器]
A --> C[进阶工具]
B --> B1(Counter 计数器)
B --> B2(defaultdict 默认字典)
B --> B3(deque 双端队列)
B --> B4(namedtuple 命名元组)
B --> B5(OrderedDict 有序字典)
C --> C1(ChainMap 链式映射)
C --> C2(UserDict/List/String 自定义封装)

📦 核心容器类

  1. Counter(计数器)

    • 功能:统计可迭代对象中元素的出现频率,返回字典形式(元素为键,计数为值)。
    • 独特方法
      • most_common(n):返回出现频率最高的前n个元素及计数。
      • 支持算术运算(如+合并计数、-消减计数)。
    • 示例
      1
      2
      3
      from collections import Counter
      words = ["apple", "banana", "apple", "orange"]
      word_count = Counter(words) # 输出:Counter({'apple': 2, 'banana': 1, 'orange': 1})
  2. defaultdict(默认字典)

    • 功能dict子类,访问不存在的键时自动生成默认值(避免KeyError)。
    • 初始化:需传入一个工厂函数(如intlistlambda)定义默认值类型。
    • 示例(分组统计):
      1
      2
      3
      4
      5
      from collections import defaultdict
      data = [("A", 10), ("B", 20), ("A", 30)]
      group = defaultdict(list)
      for key, value in data:
      group[key].append(value) # 自动初始化空列表
  3. deque(双端队列)
    (⚠️重要,不会deque把我害惨了)

    • 功能:高效支持两端插入/删除的队列,时间复杂度O(1)(优于列表的O(n))。
    • 关键方法
      • appendleft()/popleft():左端操作;
      • maxlen参数:限制队列长度,自动剔除最早元素。
    • 应用场景:滑动窗口计算、线程安全任务队列。
  4. namedtuple(命名元组)

    • 功能:创建带有字段名的元组子类,提升代码可读性。
    • 示例
      1
      2
      3
      from collections import namedtuple
      Point = namedtuple("Point", ["x", "y"])
      p = Point(1, 2) # 通过属性名访问:p.x → 1
  5. OrderedDict(有序字典)

    • 功能:记录键值对的插入顺序(Python 3.7+ 后原生dict已有序,仅旧版本需此)。
    • 特殊方法
      • move_to_end(key):将键移至末尾。

⚙️ 进阶工具类

  1. ChainMap(链式映射)

    • 功能:合并多个字典,查找时按顺序搜索。
    • 适用场景:多层配置优先级管理。
  2. UserDict / UserList / UserString

    • 功能:封装内置类型,便于自定义扩展行为(如添加校验逻辑)。