语法
迭代
iterable
可迭代对象表示的是一个对象可以一个一个地返回元素,类似一个容器。
https://docs.python.org/3/glossary.html#term-iterable
一个对象只要实现了__iter__()或__getitem__()方法就是可迭代对象。
iterator 迭代器表示的是一个流式的数据。迭代器需要有状态,需要知道当前指向数据的位置。
一个对象实现了__next__()方法就是一迭代器,Python推荐一个iterator也实现一个__iter__()返回self
lst = [1, 2, 3]
for i in lst:
print(i)在执行for…in…语句时,会首先执行iter(lst),将这个可迭代对象转换为一个迭代器
解包
def hello(name, age):
print(name, age)
args = ["Alice", 20]
kwargs = {"name": "Alice", "age": 20}
hello(*args) # Alice 20
# 相当于
hello("Alice", 20)
hello(**kwargs) # Alice 20
# 相当于
hello(name="Alice", age=20)生成器
当一个函数中有yield关键字时,这个函数就是一个生成器函数。当执行生成器函数时,会返回一个生成器对象,而不是直接执行这个函数。
生成器对象可以使用next()来执行,也可以当作一个可迭代对象在for…in…里迭代取值。当执行到yield关键字时,首先会将需要yield的值返回,然后会将yield变量的状态暂停保存,这个状态是保存在Frame上的。在生成器函数中执行return语句,相当于是raise StopIteration Exception。
def gen(num):
while num > 0:
tmp = yield num
if tmp is not None:
num = tmp
num -= 1
g = gen(5)
first = next(g) # first = g.send(None)
print(f"frist: {first}")
print(f"send: {g.send(10)}")
for i in g:
print(i)海象运算符
海象运算符-Python3.8 https://docs.python.org/zh-cn/3/whatsnew/3.8.html
if a := 15 > 10:
print('hello, walrus operator!')等价于(a的作用域不同?)
a = 15
if a > 10:
print('hello, walrus operator!')Match-Case
Match-Case→Python3.10 https://docs.python.org/zh-cn/3/whatsnew/3.10.html#pep-634-structural-pattern-matching
用法1:类似switch
def http_error(status):
match status:
case 400:
return "Bad request"
case 401 | 403 | 404:
return "Not allowed"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"用法2:case中带变量
match point:
case (0, 0):
print("Origin")
case (0, y):
print(f"Y={y}")
case (x, 0):
print(f"X={x}")
case (x, y):
print(f"X={x}, Y={y}")
case _:
raise ValueError("Not a point")函数式编程
Map-Reduce
def f(x):
return x * x
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)异步
协程概念
await
await关键字表示可以让出执行权,等待一个可等待对象(Awaitable)的执行结果,因此await关键字必须使用在可等待对象(Awaitable)前。- 通常在需要等待完成的操作时使用该关键字,这样就会让出执行权,完成异步操作。
await必须在定义了async def的协程函数中使用。
可等待对象(Awaitable):
- Coroutine:调用
async def函数得到的协程对象。 - Task:由
asyncio.create_task()等方法创建、交给事件循环调度的任务。 - Future:表示某个尚未完成的异步结果。
async def
声明了async def的函数称为coroutine function(协程函数),运行这个函数返回的是一个coroutine object(协程对象)。
协程对象coroutine object需要再转换为task才能被event loop执行。
asyncio.gather()可以直接传入协程对象coroutine object并且自动转换为task
执行任务的方法就是asyncio.run()
Coroutine
协程对象coroutine object本身是不可执行的,需要创建为task才可执行。
async def main():
# async def hello()
corotine_obj = hello()
task = asyncio.create_task(corotine_obj)
print(type(task))
await task
asyncio.run(main())Task
task是事件循环EventLoop的调度单位,Python定义task是一个协程Coroutine执行的独立任务。- 仅仅使用
await关键字修饰协程函数coroutine function是不能异步执行的,coroutine必须创建为task交给Event Loop调度才可被异步执行。
EventLoop
事件循环EventLoop是asyncio中用于调度task的循环,它会挂起等待中的task,然后将控制权交给合适的task,当异步 I/O 操作结束时,Event Loop 会再次安排它运行。
协程样例
异步请求http asycnio + aiohttp
import aiohttp
import asyncio
import numpy as np
base_url = "https://example.com/api"
paths = ["/users", "/products", "/orders", "/settings"]
original_data = list(range(100))
# 均分数据
ten_part_arr = np.array_split(original_data, 10)
async def fetch_data(session, path):
url = f"{base_url}{path}"
async with session.get(url) as response:
return await response.json() # 或根据需要处理响应
async def fetch_all():
async with aiohttp.ClientSession() as session:
# 创建4个协程对象
coroutine_objs = [fetch_data(session, path) for path in paths]
return await asyncio.gather(*coroutine_objs)
# 并发post数据
async def post_data(session, path, data):
async with session.post(url, data=data) as response:
return await response.json() # 或根据需要处理响应
async def post_all():
async with aiohttp.ClientSession() as session:
path = paths[0]
coroutine_objs = [fetch_data(session, path) for data in ten_part_arr]
return await asyncio.gather(*coroutine_objs)
# 运行异步任务
results = asyncio.run(fetch_all())
for path, result in zip(paths, results):
print(f"{path}: {result}")concurrent
concurrent.futures 多线程
import json
import urllib.request
from concurrent.futures import (
ThreadPoolExecutor,
as_completed
)
URLS = [
f"https://httpbin.org/get?id={i}"
for i in range(5)
]
def fetch(url):
"""同步 HTTP 请求函数"""
with urllib.request.urlopen(url, timeout=10) as response:
return json.loads(response.read().decode("utf-8"))
def main():
with ThreadPoolExecutor(max_workers=5) as executor:
future_to_url = {
# 安排执行,返回future对象
executor.submit(fetch, url): url
for url in URLS
}
for future in as_completed(future_to_url):
url = future_to_url[future]
try:
result = future.result()
print(url, result["args"])
except Exception as e:
print(f"请求失败: {url}, {e}")
if __name__ == "__main__":
main()
特性
闭包
在Python中,局部变量的作用域是都是Function Scope
def f():
data = []
def inner(value):
data.append(value)
return data
return inner上述函数中的inner函数调用的data为f函数定义的值,一个函数调用其他函数的定义的值称为闭包。
PEP289
只有表达式的最外层for表达式立即被计算,其他表达式被推迟到生成器运行时计算。
g = (tgtexp for var1 in exp1 if exp2 for var2 in exp3 if exp4)等价于
def __gen(bound_exp):
for var1 in bound_exp:
if exp2:
for var2 in exp3:
if exp4:
yield tgtexp
g = __gen(iter(exp1))
del __genCPython
常用库
pandas
Series
# 从列表创建
numbers = [10, 20, 30, 40, 50]
s1 = pd.Series(numbers)
# 创建带自定义索引的Series
scores = pd.Series(
[85, 92, 78, 95, 88],
index=['语文', '数学', '英语', '物理', '化学']
)读取文件
df = pd.read_csv(PATH, encoding="utf-8")DataFrame
# 从字典创建DataFrame
data = {
'姓名': ['张三', '李四', '王五', '赵六'],
'年龄': [18, 19, 20, 21],
'性别': ['男', '女', '男', '女'],
'成绩': [85, 92, 78, 95],
'城市': ['北京', '上海', '广州', '深圳']
}
df = pd.DataFrame(data)
# 选择列字段:total_amount
if 'total_amount' in df.columns:
# 点号方式选择
print(df.total_amount.head())
# 中括号列表方式选择
print(df['total_amount'].head())
# 选择多列
print(df[['date', 'category', 'total_amount']].head())
# 单条件过滤
high_amount = df[df['total_amount'] > 1000]
# 多条件过滤 - AND
filter_and = df[(df['category'] == 'Electronics') & (df['total_amount'] > 2000)]
# 多条件过滤 - OR
filter_or = df[(df['category'] == 'Electronics') | (df['category'] == 'Clothing')]
# 使用isin方法
categories = ['Electronics', 'Clothing', 'Books']
filter_isin = df[df['category'].isin(categories)]
# 按金额升序排列
sorted_asc = df.sort_values('total_amount')
# 按金额降序排列
sorted_desc = df.sort_values('total_amount', ascending=False)
# 按多列排序
print("\n按类别和金额排序:")
sorted_multi = df.sort_values(['category', 'total_amount'], ascending=[True, False])tdqm
from tqdm import tqdm
import time
# 包裹range
for i in tqdm(range(100)):
time.sleep(0.01) # 模拟耗时操作
pbar = tqdm(total=100) # 设置总数
for i in range(10):
# 模拟处理一批数据(每批10个)
time.sleep(0.1)
pbar.update(10) # 每次增加10
pbar.close() # 显式关闭(或用 with 语句更安全)
# 手动控制进度条
with tqdm(total=100) as pbar:
for i in range(10):
time.sleep(0.1)
pbar.update(10) # 增加10
# 嵌套进度条
for i in tqdm(range(3), desc="Outer"):
for j in tqdm(range(5), desc="Inner", leave=False):
time.sleep(0.05)argparse
parser = argparse.ArgumentParser(
prog='ProgramName',
description='What the program does',
epilog='Text at the bottom of help')
parser.add_argument('filename') # positional argument
parser.add_argument('-c', '--count') # option that takes a value
parser.add_argument('-v', '--verbose',
action='store_true') # on/off flagpathlib
from pathlib import Path
etc = Path('/etc')
reboot = etc / 'init.d' / 'reboot' # 拼接路径
reboot.exists() # 查询文件是否存在venv
创建venv环境,名为myenv
python3 -m venv ~/myenv启用venv环境
source ~/myenv/bin/activateuv
常用命令
# 创建项目
uv init
uv init hello-world
# 装依赖
uv sync
# 管理解释器
uv python
# 运行脚本
uv run example.py换源
在~/.config/uv/uv.toml或者/etc/uv/uv.toml填写下面的内容:
[[index]]
url = "https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple/"
default = truehf
hf download tencent/Hy-MT2-7B --local-dir
Anaconda
常用命令
#查看所有虚拟环境
conda env list
#创建一个包含numpy的环境,名字叫 myenv
conda create -n myenv numpy
#切换虚拟环境
activate myenv
#查看环境中的所有包
conda list
#安装 XXX 包
conda install XXX
#删除 XXX 包
conda remove XXX
#创建虚拟环境
conda create -n env_name jupyter notebook
#启用/激活环境
conda activate noti
activate noti
source activate noti
#删除指定环境
conda env remove -n noti
#退出环境
conda deactivate
deactivate
source deactivate
#指定python版本
conda create -n py36 python=3.6在Zsh激活环境
conda init zsh配置镜像
pip配置镜像到文件
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
首先执行
conda config --set show_channel_urls yes然后在.condarc编辑
channels:
- defaults
show_channel_urls: true
default_channels:
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
- https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloudPixi
新一代 Conda 项目管理器