Files
2026-07-28 16:19:52 +08:00

101 lines
2.8 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 第 1-8 课示例:列表
#
# 本文件使用 Agent 开发工具作为统一示例,演示列表的主要操作。
# 示例无需用户输入,可以直接运行并对照注释观察结果。
# 一、创建列表并读取元素
agent_tools = ["Python", "FastAPI", "Django"]
print(f"完整工具列表:{agent_tools}")
print(f"工具数量:{len(agent_tools)}")
print(f"第一个工具:{agent_tools[0]}")
print(f"最后一个工具:{agent_tools[-1]}")
# 二、切片返回一个新列表
backend_tools = agent_tools[1:]
print(f"后端框架切片:{backend_tools}")
# 三、修改指定位置的元素
# 列表是可变对象,可以直接修改已有索引对应的元素。
agent_tools[2] = "Pydantic"
print(f"修改后的列表:{agent_tools}")
# 四、添加元素
agent_tools.append("Django")
agent_tools.insert(1, "Git")
agent_tools.extend(["LangChain", "OpenAI SDK"])
print(f"添加后的列表:{agent_tools}")
# 五、删除元素
# remove() 按内容删除pop() 按位置删除并返回被删除的数据。
if "Git" in agent_tools:
agent_tools.remove("Git")
removed_tool = agent_tools.pop()
print(f"pop() 删除的工具:{removed_tool}")
print(f"删除后的列表:{agent_tools}")
# 六、查找和统计
contains_fastapi = "FastAPI" in agent_tools
fastapi_index = agent_tools.index("FastAPI")
python_count = agent_tools.count("Python")
print(f"是否包含 FastAPI{contains_fastapi}")
print(f"FastAPI 的索引:{fastapi_index}")
print(f"Python 出现次数:{python_count}")
# 七、排序和反转
# sorted() 返回新列表,不改变原列表。
sorted_tools = sorted(agent_tools)
print(f"原列表:{agent_tools}")
print(f"排序后的新列表:{sorted_tools}")
# reverse() 直接修改当前列表顺序。
agent_tools.reverse()
print(f"反转后的原列表:{agent_tools}")
# 八、直接遍历元素
for tool in agent_tools:
print(f"正在学习:{tool}")
# 九、使用 enumerate() 同时取得编号和元素
for number, tool in enumerate(agent_tools, start=1):
print(f"{number}. {tool}")
# 十、简单二维列表
# 每条内部列表保存工具名称和用途。
tool_records = [
["Python", "基础编程"],
["FastAPI", "接口开发"],
["Django", "Web 应用"],
]
for record in tool_records:
print(f"工具:{record[0]},用途:{record[1]}")
# 十一、直接赋值与复制
# alias_tools 和 original_tools 指向同一个列表。
original_tools = ["Python", "FastAPI"]
alias_tools = original_tools
alias_tools.append("Django")
print(f"直接赋值后的原列表:{original_tools}")
print(f"直接赋值后的别名列表:{alias_tools}")
# copy() 为简单列表创建独立副本。
copied_tools = original_tools.copy()
copied_tools.append("LangChain")
print(f"复制后保持不变的原列表:{original_tools}")
print(f"修改后的副本:{copied_tools}")