跳到主内容

LangChain Python

最后更新: 2026-10-11

1. 元组

元组(tuple)也是一种有序集合,可以保存多个值。它和列表很像,都支持索引、切片和遍历,但元组创建后不能直接修改其中的元素。

使用圆括号创建元组:

create.py
1
point = (10, 20)
2
topics = ("变量", "列表", "元组")
3
empty = ()
4
5
print(point)
6
print(topics)
7
print(empty)

圆括号在很多场景中可以省略,逗号才是元组结构的重要标记:

comma.py
1
point = 10, 20
2
3
print(point) # (10, 20)
4
print(type(point)) # <class 'tuple'>

创建只有一个元素的元组时,必须保留逗号。没有逗号的 ("Python") 只是普通字符串加上括号:

single.py
1
single_tuple = ("Python",)
2
not_tuple = ("Python")
3
4
print(type(single_tuple)) # <class 'tuple'>
5
print(type(not_tuple)) # <class 'str'>

也可以使用 tuple() 把其他可遍历对象转换成元组:

convert.py
1
letters = tuple("Python")
2
numbers = tuple(range(3))
3
4
print(letters) # ('P', 'y', 't', 'h', 'o', 'n')
5
print(numbers) # (0, 1, 2)

2. 访问

元组的索引和切片规则与列表、字符串一致,索引从 0 开始:

access.py
1
topics = ("变量", "列表", "元组", "字符串")
2
3
print(topics[0]) # 变量
4
print(topics[-1]) # 字符串
5
print(topics[1:3]) # ('列表', '元组')

可以使用 len() 获取元组长度,使用 in 判断元素是否存在:

inspect.py
1
permissions = ("read", "write")
2
3
print(len(permissions)) # 2
4
print("read" in permissions) # True
5
print("admin" not in permissions) # True

元组支持 count() 和 index():

methods.py
1
values = ("Python", "AI", "Python")
2
3
print(values.count("Python")) # 2
4
print(values.index("AI")) # 1

如果 index() 找不到目标元素,会抛出 ValueError。不确定元素是否存在时,先使用 in 判断。

3. 不可变

元组最重要的特征是不可变。创建之后,不能给某个位置重新赋值,也不能使用 append()、remove() 等方法修改结构:

immutable.py
1
topics = ("变量", "列表", "元组")
2
3
# topics[0] = "模块" # TypeError
4
# topics.append("字符串") # AttributeError

如果确实需要得到一个加入新元素的结果,应该创建一个新的元组:

new-tuple.py
1
topics = ("变量", "列表")
2
new_topics = topics + ("元组",)
3
4
print(topics) # ('变量', '列表')
5
print(new_topics) # ('变量', '列表', '元组')

这里的 + 不会修改原元组,而是返回一个新的元组。单元素元组中的逗号不能省略。

元组不可变,但如果元组里面保存的是列表,列表本身仍然可以修改:

nested-mutable.py
1
data = ("topics", ["变量", "列表"])
2
data[1].append("元组")
3
4
print(data) # ('topics', ['变量', '列表', '元组'])

不可变的是元组保存的元素引用,不能通过元组索引替换第二个元素;内部列表作为独立对象,仍然保留自己的可变性。

4. 解包

元组经常用于一次性保存一组固定值,也经常用于解包:把元组中的元素依次赋给多个变量:

unpack.py
1
point = (10, 20)
2
x, y = point
3
4
print(x) # 10
5
print(y) # 20

左侧变量的数量必须和右侧元素数量匹配,否则会抛出 ValueError:

unpack-error.py
1
values = (1, 2, 3)
2
3
# first, second = values # ValueError

如果只关心一部分元素,可以使用 * 收集剩余内容:

starred.py
1
values = (1, 2, 3, 4, 5)
2
first, *middle, last = values
3
4
print(first) # 1
5
print(middle) # [2, 3, 4]
6
print(last) # 5

带 * 的变量得到的是列表,而不是元组。一个解包表达式中通常只使用一个带 * 的变量。

函数可以返回多个值,Python 实际上会把它们组合成元组:

return-values.py
1
def get_user():
2
return "小明", 18
3
4
name, age = get_user()
5
print(name)
6
print(age)

这种写法比手动创建一个临时对象更简洁,适合返回几个关系紧密的结果。

5. 对比

列表和元组都可以保存有序数据,但用途有所不同:

对比项列表元组
创建符号[]()
是否有序是是
是否可修改可以不可以
常用场景数据需要增删改数据结构固定
是否支持索引切片支持支持
是否可作为字典键通常不可以元素都可哈希时可以

需要不断添加任务、删除结果或重新排序时,使用列表更合适:

list-choice.py
1
tasks = ["读取文件", "保存结果"]
2
tasks.append("发送通知")
3
4
print(tasks)

表示坐标、配置项、日期或函数返回的固定组合时,元组更能表达「这些位置和数量不会随意变化」的意图:

tuple-choice.py
1
rgb = (255, 128, 0)
2
version = (3, 12, 1)
3
4
print(rgb)
5
print(version)

元组中的元素都可哈希时,可以作为字典的键。列表因为可变,不能直接作为字典键:

dict-key.py
1
locations = {
2
(31.23, 121.47): "上海",
3
(39.90, 116.40): "北京",
4
}
5
6
print(locations[(31.23, 121.47)]) # 上海

6. 使用

元组可以直接遍历,也可以和 enumerate() 一起使用:

loop.py
1
topics = ("变量", "列表", "元组")
2
3
for index, topic in enumerate(topics, start=1):
4
print(f"第 {index} 个主题:{topic}")

在处理固定结构的数据时,可以把元组解包后再使用:

records.py
1
records = (
2
("小明", 82),
3
("小红", 95),
4
("小李", 58),
5
)
6
7
for name, score in records:
8
if score >= 60:
9
print(f"{name}:通过")

下面的例子使用元组保存固定的状态值,再用字典把状态值映射为展示文本:

status.py
01
statuses = ("pending", "running", "success", "failed")
02
labels = {
03
"pending": "等待中",
04
"running": "执行中",
05
"success": "执行成功",
06
"failed": "执行失败",
07
}
08
09
for status in statuses:
10
print(labels[status])

FastAPI 接口和 LangChain 工具中也经常返回固定结构的多个结果。例如把状态和消息一起返回,再由调用方解包:

result.py
1
def run_task():
2
return True, "任务执行成功"
3
4
success, message = run_task()
5
if success:
6
print(message)

当返回值的数量和含义稳定时,元组可以让调用方一眼看出数据结构;如果字段很多、需要按名称访问,则更适合使用字典或数据模型。

7. 在线元组实验

用坐标和任务状态观察元组的固定结构。接口会把 Python 的类型名与 repr() 一起返回,避免只看 JSON 数组而误以为 Python 中保存的也是列表。

案例项目文件
使用上下方向键浏览目录,左右方向键展开或收起,Enter 或空格切换展开状态。
    • main.pyFastAPI 接口与请求参数校验
    • tuples_demo.py本篇主题的 Python 实验
    • pyproject.toml项目与基础依赖配置
    • .python-version本机 Python 3.12
    • .gitignore忽略环境与生成文件
    • README.md运行步骤与边界说明

7.1 完整案例代码

main.py 提供接口,tuples_demo.py 执行实验。下面展示的代码与在线编辑器的初始文件来自同一份源码;修改编辑器中的文件后,保存并重新运行,接口就会使用修改后的内容。

main.py
01
from typing import Literal
02
03
from fastapi import FastAPI, Query
04
05
from tuples_demo import build_report
06
07
app = FastAPI()
08
09
@app.get("/tuples")
10
async def tuples(
11
x: int = Query(10, ge=-10000, le=10000),
12
y: int = Query(20, ge=-10000, le=10000),
13
status: Literal["pending", "running", "success", "failed"] = "running",
14
) -> dict[str, object]:
15
report = build_report(x, y, status)
16
print(f"坐标元组:{report['point']['repr']}")
17
print(f"星号解包中间值类型:{report['starred']['middle_type']}")
18
print(f"索引赋值的捕获结果:{report['immutable_error']}")
19
return report
20
tuples_demo.py
01
def describe(value: tuple) -> dict[str, object]:
02
return {"type": type(value).__name__, "repr": repr(value), "items": list(value)}
03
04
def task_result(status: str) -> tuple[bool, str]:
05
labels = {"pending": "等待中", "running": "执行中",
06
"success": "执行成功", "failed": "执行失败"}
07
return status == "success", labels[status]
08
09
def build_report(x: int, y: int, status: str) -> dict[str, object]:
10
point = (x, y)
11
unpacked_x, unpacked_y = point
12
first, *middle, last = (1, 2, 3, 4, 5)
13
success, message = task_result(status)
14
15
try:
16
point[0] = 0
17
except TypeError as error:
18
immutable_error = type(error).__name__
19
20
# 元组的元素引用不变,但其中的列表对象仍然可以修改。
21
nested = ("topics", ["变量", "列表"])
22
before_nested = repr(nested)
23
nested[1].append("元组")
24
25
# 元组键留在 Python 内部;响应返回查找结果,不直接序列化这个字典。
26
locations = {point: "当前坐标"}
27
return {
28
"point": describe(point),
29
"unpacked": {"x": unpacked_x, "y": unpacked_y},
30
"single": describe(("Python",)),
31
"without_comma": {"type": type(("Python")).__name__, "value": ("Python")},
32
"slice": describe(point[:1]),
33
"extended": describe(point + (30,)),
34
"immutable_error": immutable_error,
35
"nested_mutable": {"before": before_nested, "after": repr(nested)},
36
"starred": {"first": first, "middle": middle, "last": last,
37
"middle_type": type(middle).__name__},
38
"tuple_key": {"key_repr": repr(point), "value": locations[point]},
39
"returned_values": {"success": success, "message": message,
40
"python_type": type(task_result(status)).__name__},
41
}
42
43
if __name__ == "__main__":
44
import json
45
46
print(json.dumps(build_report(10, 20, "running"), ensure_ascii=False, indent=2))
47

7.2 运行与观察

打开本篇在线案例,点击运行并等待环境就绪。案例预览默认选择 GET,地址为:

code.ts
1
/tuples?x=10&y=20&status=running

默认响应中,point.type 为 tuple,point.repr 为 "(10, 20)";single.type 是 tuple,without_comma.type 是 str。starred.middle 是 [2, 3, 4],middle_type 为 list。immutable_error 为 TypeError,它是已经捕获的教学结果,接口不会因此失败。

日志会打印对应的关键操作结果。把 x 和 y 改为 31、121,观察坐标与元组键查询结果变化;把 status 改为 success,returned_values.success 会变成 true,message 为 "执行成功"。也可以修改 tuples_demo.py 中的元组内容,保存并重新运行后观察解包结果。

status 只允许 pending、running、success、failed,其余值返回 HTTP 422。JSON 没有元组类型,所以 items 明确转成列表,type 与 repr 才说明 Python 里原本的类型。nested_mutable 演示修改内部列表,不是在替换元组元素。元组键字典只在 Python 中查询,不直接作为 JSON 对象返回。

7.3 在本机继续运行

本案例只使用标准库、FastAPI 与 Pydantic,不需要模型密钥。下载并解压 ZIP,进入项目目录后执行:

code.ts
1
uv run python tuples_demo.py
2
uv run fastapi dev main.py

第一条直接在终端打印实验结果;第二条启动 FastAPI。打开 http://127.0.0.1:8000/docs,选择 GET /tuples,填写同样的参数即可发起请求。本机使用 Python 3.12,浏览器使用当前 Pyodide 版本,通过 HTTPX ASGITransport 执行接口,不启动电脑上的 8000 端口。

本篇的代码、日志、Git 配置与 PI Agent 对话使用独立工作区;同站 Python 依赖缓存可以复用。本机配置文件、忽略规则和 README 都包含在项目中,可以在文件目录里查看、编辑和下载。

正在验证登录状态
请稍候,验证完成后将继续显示文章内容

此段落已有评论,按 Enter 查看评论及回复列表。

评论-

文章反应
评论与回复

连接 GitHub 后查看和发表评论,也可在 GitHub 查看公开讨论。

添加评论
    即时渲染