Python 小知识点

获取文件后缀

1
2
3
import os

suffix = os.path.splitext("hello.pdf")[1]

输出 .pdf.

生成随机数

random 标准库

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import random

# 随机浮点数, 范围在 [0.0, 1.0]
random_float = random.random()
print(random_float)

# 指定范围的随机浮点数
random_uniform = random.uniform(1.0, 10.0) # 生成 1.0 到 10.0 之间的随机浮点数
print(random_uniform)

# 随机整数
random_int = random.randint(1, 10) # 生成 1 到 10 之间的随机整数
print(random_int)

# 从列表中随机选择一个元素
items = ['apple', 'banana', 'cherry']
random_choice = random.choice(items)
print(random_choice)

# 从列表中随机选择多个元素
items = [1, 2, 3, 4, 5, 6]
random_samples = random.sample(items, 3) # 随机选择 3 个元素
print(random_samples)

lorem-text 随机生成字符

利用 lorem-text 库可以生成指定个数的随机段落, 随机单词, 安装如:

1
pip install lorem-text

示例:

1
2
3
4
5
from lorem_text import lorem

words_length = 10
sentence = lorem.words(words_length)
print(sentence)

uuid

1
2
3
4
5
6
7
8
9
10
11
12
13
import uuid

# 生成一个随机 UUID(UUID4)
random_uuid = uuid.uuid4()
print("随机 UUID:", random_uuid)

# 生成一个基于名字的 UUID(UUID5)
name_based_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, 'example.com')
print("基于名字的 UUID:", name_based_uuid)

# 生成一个基于时间的 UUID(UUID1)
time_based_uuid = uuid.uuid1()
print("基于时间的 UUID:", time_based_uuid)

将 datetime 对象转字符串

1
2
3
4
5
6
7
8
9
import datetime

# 示例 datetime 对象
update_time = datetime.datetime(2024, 8, 31, 23, 4, 24, 187817)

# 转换为字符串
formatted_time = update_time.strftime("%m-%d %H:%M:%S")

print(formatted_time)

遍历数组并获取索引和元素

1
2
3
4
5
6
# 示例数组
arr = ['apple', 'banana', 'cherry']

# 遍历数组并获取索引和元素
for index, value in enumerate(arr):
print(f"Index: {index}, Value: {value}")
  • enumerate() 函数会遍历一个数组 (列表) 并获取每个元素及其索引

定义函数接受关键字参数

一般的函数定义为:

1
2
def hello(arg1: str, srg2: str):
...

此时接收的是位置参数, 即传递给哪个形参是靠位置判断:

1
hello("jie", "orkarin")

(这里把 “jie” 传给 arg1, 把 “orkarin” 传给 arg2)

若用关键字参数则为:

1
2
def hello(*, arg1: str, srg2: str):
...

此时调用为:

1
hello(arg1="jie", arg2="orkarin")

导入当前目录的一个文件

1
from . import models

意思是, 从当前执行的 Python 文件所在目录下, 导入 models.py 文件.

而:

1
from .db import engine

表明从 db.py 文件中导入 engine 变量.

Annotated 类型构造器

Annotated 是 Python 标准库 typing 模块提供的一个类型构造器, 其允许为类型注解附加额外的元数据信息.

语法为:

1
2
3
fron typing import Annotated

AnnotatedType = Annotated([BaseType, Annotation1, Annotation2, ...])
  • BaseType 是想要注解的基本类型, 如 int, str, List[int] 等。
  • Annotation1, Annotation2 等是您想要附加的元数据信息, 可以是任意的 Python 对象

Union 类型构造器

Union 是 Python 的标准库 typing 模块中提供的类型构造器, 用于表示一个值可以是多种情况之一的情况.

比如 q: Union[str, None] 表示 q 参数可以是 str 类型, 也可以是 None.

字典展开

** 操作符:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from fastapi import FastAPI
from pydantic import BaseModel


class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None


app = FastAPI()


@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}

这里的 **item.dict() 实际上等价于 name='Example', description='This is an example', price=9.99, tax=1.2.

格式化输出

使用 %

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
name = "Alice"
age = 30

# 字符串格式化
print("Hello, %s!" % name)
# 输出: Hello, Alice!

# 多个变量格式化
print("Name: %s, Age: %d" % (name, age))
# 输出: Name: Alice, Age: 30

# 浮点数格式化
pi = 3.141592653589793
print("Pi: %.2f" % pi)
# 输出: Pi: 3.14

使用 str.format()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
name = "Alice"
age = 30

# 字符串格式化
print("Hello, {}!".format(name))
# 输出: Hello, Alice!

# 多个变量格式化
print("Name: {}, Age: {}".format(name, age))
# 输出: Name: Alice, Age: 30

# 指定位置
print("Name: {0}, Age: {1}".format(name, age))
# 输出: Name: Alice, Age: 30

# 关键字参数
print("Name: {name}, Age: {age}".format(name=name, age=age))
# 输出: Name: Alice, Age: 30

# 浮点数格式化
pi = 3.141592653589793
print("Pi: {:.2f}".format(pi))
# 输出: Pi: 3.14

使用 f-string

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
name = "Alice"
age = 30

# 字符串格式化
print(f"Hello, {name}!")
# 输出: Hello, Alice!

# 多个变量格式化
print(f"Name: {name}, Age: {age}")
# 输出: Name: Alice, Age: 30

# 表达式支持
print(f"Next year, {name} will be {age + 1} years old.")
# 输出: Next year, Alice will be 31 years old.

# 浮点数格式化
pi = 3.141592653589793
print(f"Pi: {pi:.2f}")
# 输出: Pi: 3.14

map 和 list 函数

list 函数

用于创建列表, 可以将其他可迭代对象转换成列表数据结构:

1
list([iterable])

如:

1
2
3
4
5
6
7
8
9
10
11
# 从字符串创建列表
string_to_list = list("hello")
print(string_to_list) # 输出: ['h', 'e', 'l', 'l', 'o']

# 从元组创建列表
tuple_to_list = list((1, 2, 3))
print(tuple_to_list) # 输出: [1, 2, 3]

# 从集合创建列表
set_to_list = list({4, 5, 6})
print(set_to_list) # 输出: [4, 5, 6]

若创建指定长度的列表, 可:

1
2
3
# 创建指定长度的列表,并用 0 填充
filled_list = list([0] * 5)
print(filled_list) # 输出: [0, 0, 0, 0, 0]

map 函数

map() 可以对可迭代对象 (如列表, 元组, 字符串等) 中的每个元素应用一个函数, 返回一个新的可迭代对象.

如:

1
2
3
4
# 将列表中的每个元素乘以 2
numbers = [1, 2, 3, 4, 5]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers) # 输出: [2, 4, 6, 8, 10]

Set 数据结构

简介

集合 (Set) 是 Python 中一种内置的数据结构, 它是一个无序的, 不重复的元素集合. 集合中的元素必须是不可变的 (immutable) 数据类型, 如整数, 浮点数, 字符串, 元组等.

一般可以使用 set 来去除 list 中的重复元素.

set() 函数

set() 函数用于创建一个集合, 也可用于去除 list 中的重复元素如:

1
2
3
A = [1, 1, 2, 2, 3, 3]
setA = set(A)
print(setA)

generator

简介

Python 中的生成器是一种特殊的函数, 它可以用来生成一系列的值, 而不是像普通函数那样返回一个单一的值. 生成器使用 yield 关键字, 而不是 return 关键字.

Generator 是 “惰性计算” 的, 即只会在需要时才会计算下一个值, 因此生成器可以处理很大的数据集, 而不会占用太大内存.

简单示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1

# 使用生成器
counter = count_up_to(5)
print(next(counter)) # 输出 0
print(next(counter)) # 输出 1
print(next(counter)) # 输出 2
print(next(counter)) # 输出 3
print(next(counter)) # 输出 4
print(next(counter)) # 触发 StopIteration 异常

next() 函数

用于手动获取生成器的下一个值, 当生成器返回完所有值时,会抛出 StopIteration 异常.

sum(), max(), min() 等函数

这些聚合函数可以直接作用于生成器,因为生成器是可迭代的.

1
2
3
4
5
6
7
8
9
10
11
12
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1

counter = count_up_to(10)
print(sum(counter)) # 输出 45
counter = count_up_to(10)
print(max(counter)) # 输出 9
counter = count_up_to(10)
print(min(counter)) # 输出 0

pdb 调试器

简介

pdb (Python Debugger), 是 Python 标准库中自带的调试工具, 可以支持断点设置, 查看变量值, 单步执行等功能.

示例

pdb.set_trace() 设置断点:

1
2
3
4
5
6
7
8
9
# pdb_test.py
import pdb

def my_function(a, b):
pdb.set_trace() # 在这里设置断点
result = a + b
return result

my_function(2, 3)

此时运行:

1
2
$ python pdb_test.py
> /path/to/pdb_test.py(3)my_function()-> result = a + b

之后可以通过:

  • l (list) - 列出当前位置附近的源代码
  • n (next) - 执行当前语句,但不进入函数
  • s (step) - 进入函数内部,单步执行
  • c (continue) - 继续执行程序,直到遇到下一个断点
  • p (print) - 打印变量的值
  • pp (pretty print) - 以更加美观的格式打印变量的值
  • bt (backtrace) - 显示当前调用栈信息
  • q (quit) - 退出调试器

collections 模块

简介

collections 模块是 Python 标准库中的一个模块, 其提供了一些特殊的数据结构.

defaultfict

defaultfict 是一个特殊的字典 (dictionary) 类型. 它与普通的字典类型 (dict) 的主要区别在于, 当你试图访问一个不存在的键时, defaultdict 会自动创建并初始化这个键, 而不会抛出 KeyError 异常.

如:

1
2
3
4
5
6
7
8
9
10
11
12
13
from collections import defaultdict

# 创建一个 defaultdict,初始值为空列表
d = defaultdict(list)

# 添加一些键值对
d["apple"].append("red")
d["apple"].append("green")
d["banana"].append("yellow")

# 打印字典内容
print(d)
# 输出: defaultdict(<class 'list'>, {'apple': ['red', 'green'], 'banana': ['yellow']})

sorted 函数

介绍

sorted() 函数可用于对可迭代对象, 如列表, 元组, 字符串等进行排序.

语法为:

1
sorted(iterable, /, *, key=None, reverse=False)

主要关注:

  • iterable, 可迭代对象
  • key, 一个函数, 会被应用到 iterable 中的每个元素上, 然后根据函数返回值进行排序
  • reverse, 如果 reverse 参数设置为 True, 则返回的列表将是降序排列
    其他两个似乎可以忽略.

注意 sorted() 的返回值是一个列表. 如施加在字符串上:

1
2
3
4
str = "hello"
A = sorted(str)
print(A)
# 输出: ['e', 'h', 'l', 'l', 'o']

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 对列表排序
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # 输出: [1, 2, 5, 8, 9]

# 对字符串排序
words = ["apple", "banana", "cherry", "date"]
sorted_words = sorted(words)
print(sorted_words) # 输出: ['apple', 'banana', 'cherry', 'date']

# 按字符串长度排序
sorted_words = sorted(words, key=len)
print(sorted_words) # 输出: ['date', 'apple', 'banana', 'cherry']

# 降序排列
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers) # 输出: [9, 8, 5, 2, 1]

join 函数

语法为:

1
'separator'.join(iterable)

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 将列表中的元素连接成一个字符串
words = ['apple', 'banana', 'cherry']
result = '-'.join(words)
print(result) # 输出: 'apple-banana-cherry'

# 将元组中的元素连接成一个字符串
numbers = (1, 2, 3, 4, 5)
result = ' + '.join(map(str, numbers))
print(result) # 输出: '1 + 2 + 3 + 4 + 5'

# 连接字符串
chars = 'abc'
result = ','.join(chars)
print(result) # 输出: 'a,b,c'

同时返回序列的索引和值

enumerate() 函数, 如:

1
2
3
4
5
6
7
8
9
10
fruits = ['apple', 'banana', 'cherry']

# 使用 enumerate() 函数获取索引和值
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Value: {fruit}")

# 输出结果:
# Index: 0, Value: apple
# Index: 1, Value: banana
# Index: 2, Value: cherry

/// 的区别

/ 除法运算符会执行标准浮点数除法:

1
2
print(10 / 3)    # 输出: 3.3333333333333335
print(5.0 / 2) # 输出: 2.5

// 执行整除运算, 只有当有一个操作数为浮点数时, 输出为浮点数:

1
2
print(10 // 3)   # 输出: 3
print(5.0 // 2) # 输出: 2.0

注意 python 的取模运算符是 %.

从 STDIN 获取输入

使用 input(), 如:

1
2
nA, nB = map(int, input().split())
print(str(nA)+" "+str(nB))

此时若输入 1 2, 则会拆分后分别赋值给 nAnB.

print() 函数

如:

1
print('The length of %s is %d' %(s,x))

这里的%(s,x),其中%标记转换说明符的开始,(s,x)为转换说明符。

可以一次输出多个对象:

1
print(a, b)

可直接输出列表,字典,元组等变量。

最小字段宽度和精度设置和C语言相同。

try … except

将可能发生错误的语句放在try模块,用except处理异常。

except 可以指定一个专门的异常,若未指定则默认为所有异常。

每一个try都至少要有一个except.

可以多分支.

若使用 try ... except ... finally, finally 部分无论 try 是否捕获错误都会执行。

except 中的 as 应该是设置别名。

字符串单引号和双引号

两者皆可。

range(x, y, z)

z是步长量。

转换类型

如:

1
self.R = int(R)

Python 缩进

Python 用缩进来区分代码层次。

-m 选项

使用 -m 选项时,Python 会把当前工作目录添加到 sys.path 中。

isinstance() 函数

用于判断一个对象是否为一个已知类型。

语法:

1
isinstance(object, classinfo) 

返回布尔值。

type() 的区别:

  • type() 不考虑继承关系,不会认为子类是一种父类类型
  • isinstance() 考虑继承关系,认为子类是一种父类类型

Python 小知识点
http://example.com/2022/08/22/Python-小知识点/
作者
Jie
发布于
2022年8月22日
许可协议