Python列表与AI接口实战:从基础到应用
一、引言
Python作为一门简洁优雅的编程语言,在数据分析、机器学习等领域广泛应用。本文将通过Jupyter Notebook的实战案例,深入讲解Python列表的基本操作、切片语法,以及如何利用AI接口完成实际任务。
二、Python列表基础
2.1 列表的特点
Python中比较灵活的数据结构是list,而Array很少使用。列表与JavaScript中的Array非常相似:
python
L = ["cao", "laiqingqing", "zhouwenqiang", "hongzhongshe"]
列表的核心特性:
| 特性 | 说明 |
|---|---|
| 动态长度 | 无需提前指定容量 |
| 类型灵活 | 值的类型不受约束 |
| 有序可修改 | 支持索引访问和增删改操作 |
2.2 与JavaScript的对比
JavaScript借鉴了Python的很多特性,但两者擅长的领域不同:
- JavaScript:适合做页面展示和交互,不适合做计算(Number类型,没有浮点数类型)
- Python:适合机器学习、爬虫、数据分析,有高精度数值类型
python
# 遍历取值
r = []
n = 3
for i in range(n):
r.append(L[i])
r # ['cao', 'laiqingqing', 'zhouwenqiang']
三、切片操作详解
3.1 什么是切片
切片(Slice)大大简化了取部分元素的操作,是Python最强大的特性之一。
python
L = ["cao", "laiqingqing", "zhouwenqiang", "hongzhongshe"]
L[0:3] # ['cao', 'laiqingqing', 'zhouwenqiang']
L[:3] # 等价于 L[0:3]
L[1:3] # ['laiqingqing', 'zhouwenqiang']
L[-2:] # ['zhouwenqiang', 'hongzhongshe']
3.2 切片语法
arduino
list[start:end:step]
start:起始索引(包含)end:结束索引(不包含)step:步长,默认为1
3.3 实战案例:range生成列表
python
L = list(range(100))
L[:10] # 前10个元素
L[-10:] # 后10个元素
L[:10:2] # 前10个,每隔1个取1个
L[::5] # 每隔5个取1个
3.4 切片的妙用:字符串处理
切片不仅适用于列表,还适用于字符串:
python
'ABCDEFG'[:3] # 'ABC'
'ABCDEFG'[::2] # 'ACEG'
# 利用切片实现字符串去空格(双指针思想)
def trim(s):
left = 0
while left < len(s) and s[left] == ' ':
left += 1
right = len(s)
while right > left and s[right - 1] == ' ':
right -= 1
return s[left:right]
print(trim(" hello world ")) # 'hello world'
四、ModelScope与LLM接口
4.1 ModelScope简介
ModelScope是阿里开源模型发布社区,寓意"模型空间":
- Model:模型
- Scope:空间
- 提供开源模型、数据集合
- 支持NLP实验
4.2 LLM厂商介绍
| 厂商 | 特点 |
|---|---|
| OpenAI | 基于Google开源的Transformer架构,引领2022年底生成式AI浪潮 |
| DeepSeek | 兼容OpenAI接口 |
| Gemini | Google出品 |
| Claude | Anthropic出品,各有特色 |
4.3 API调用实战
ModelScope内置了兼容OpenAI的接口:
python
from openai import OpenAI
client = OpenAI(
api_key="your-api-key",
base_url="https://api.deepseek.com/v1"
)
COMPLETION_MODEL = "deepseek-chat"
def get_response(prompt):
response = client.chat.completions.create(
model = COMPLETION_MODEL,
messages=[
{"role": "user", "content": prompt}
]
)
return response.choices[0].message.content
五、Prompt工程最佳实践
5.1 Prompt编写原则
编写高质量的Prompt需要遵循以下原则:
- 清晰且详细的表达目标:越具体越好,避免模糊表述
- 分步骤:使用"1、2、3、"或"首先、其次、最后"
- 约束输出格式:指定JSON格式,字段名要清晰
5.2 实战案例:产品描述生成
python
prompt = """
Consideration product:
工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光蛙儿童水上玩具
1. Compose human readable product title used on Amazon in english within 20 words.
2. Write 5 selling points for the products in Amazon
3. Evaluate a price range for this product in U.S.
Output the result in json format with three properties called title, selling_points and price_range
"""
输出结果:
json
{
"title": "LED Light-Up Inflatable Frog Toy for Kids -- PVC Water Fun for Pool, Beach & Night Market",
"selling_points": [
"Eye-catching built-in LED lights make this frog glow in the dark...",
"Made from durable PVC material...",
"Lightweight and easy to inflate...",
"Fun and affordable novelty design...",
"Safe for children ages 3 and up..."
],
"price_range": "$5.99 -- $12.99"
}
5.3 Prompt优化技巧
| 技巧 | 说明 |
|---|---|
| 细化目标 | 不要说"写得好",要说"用5个bullet points描述" |
| 指定格式 | JSON比纯文本更利于程序处理 |
| 角色设定 | 可以让AI扮演特定角色 |
| 示例引导 | 提供few-shot示例 |
六、Notebook开发环境
6.1 Notebook的优势
Notebook文件(.ipynb)结合了Markdown和代码:
- 边写代码边记笔记
- 适合数据分析、学习、写报告
- 所见即所得的交互式开发环境
6.2 工作流程
python
# Cell 1: 基础打印
print("My first NoteBook")
# Cell 2: 列表操作
L = ["cao", "laiqingqing", "zhouwenqiang"]
r = []
n = 3
for i in range(n):
r.append(L[i])
r
# Cell 3: 切片操作
L = list(range(100))
L[:10]
七、总结
通过本文的学习,我们掌握了:
- Python列表:灵活的数据结构,支持动态长度和类型混合
- 切片操作:强大的索引功能,简化元素提取
- AI接口:利用ModelScope调用LLM完成实际任务
- Prompt工程:清晰、分步、格式化的Prompt编写原则
这些技能为后续的数据分析和AI应用开发奠定了坚实基础。