从 Python List 到 LLM 接口:一条被忽视的 AI 入门捷径

从切片到 API:一个 Python 新手如何用 30 行代码调用大模型

别被"大模型开发"吓到,它的起点可能就是一行 L[:3]

今天分享一个完整的学习路径:
从 Python 切片语法 → 手写 trim 函数 → 调用 DeepSeek API 生成亚马逊商品文案

全程不超 50 行代码,但每一步都有真实收获。


目录

  1. [Python List vs 传统数组](#Python List vs 传统数组 "#%E4%B8%80python-list-vs-%E4%BC%A0%E7%BB%9F%E6%95%B0%E7%BB%84")
  2. [切片:Python 最性感的语法](#切片:Python 最性感的语法 "#%E4%BA%8C%E5%88%87%E7%89%87python-%E6%9C%80%E6%80%A7%E6%84%9F%E7%9A%84%E8%AF%AD%E6%B3%95")
  3. [实战:手写 trim 函数](#实战:手写 trim 函数 "#%E4%B8%89%E5%AE%9E%E6%88%98%E6%89%8B%E5%86%99-trim-%E5%87%BD%E6%95%B0")
  4. [跃迁:调用大模型 API](#跃迁:调用大模型 API "#%E5%9B%9B%E8%B7%83%E8%BF%81%E8%B0%83%E7%94%A8%E5%A4%A7%E6%A8%A1%E5%9E%8B-api")
  5. [DeepSeek vs OpenAI vs 其他](#DeepSeek vs OpenAI vs 其他 "#%E4%BA%94deepseek-vs-openai-vs-%E5%85%B6%E4%BB%96")
  6. 代码优化与最佳实践
  7. 完整代码

一、Python List vs 传统数组

1.1 Python 没有内置数组

很多从 Java/C++ 转 Python 的人会问:Python 的数组在哪?

答案:Python 没有 Java/C++ 那样的内置数组,但它有更强大的 list

特性 Java/C++ 数组 Python list
长度 固定,创建后不可变 动态,自动扩容
类型 必须统一 任意类型混放
内存 连续内存 对象引用数组
性能 访问快,操作受限 灵活但略慢
切片 需要手动循环 原生支持

1.2 List 的核心特性

python 复制代码
# 1. 动态长度(无需指定容量)
L = []                    # 空列表
L.append("曹辉")          # 自动扩容
L.extend(["赖庆庆", "周文强"])  # 批量添加

# 2. 类型自由
mix = [42, "hello", 3.14, [1, 2], True]

# 3. 有序且可修改
L[0] = "新名字"           # 修改
del L[1]                 # 删除

1.3 List 常用操作速查

python 复制代码
# 增
L.append(x)          # 末尾添加
L.insert(i, x)       # 指定位置插入
L.extend(iterable)   # 批量添加

# 删
L.pop()              # 弹出末尾
L.pop(i)             # 弹出索引 i
L.remove(x)          # 删除第一个值为 x 的元素
del L[i:j]           # 删除切片
L.clear()            # 清空

# 改
L[i] = new_value     # 索引赋值
L[i:j] = [a,b,c]     # 切片赋值

# 查
L.index(x)           # 查找索引
x in L               # 判断是否存在
L.count(x)           # 计数

二、切片:Python 最性感的语法

2.1 切片基础

python 复制代码
L = ["曹辉", "赖庆庆", "周文强", "徐波", "宏"]

# 基本语法:L[start:end:step]
print(L[0:3])   # ['曹辉', '赖庆庆', '周文强'](不含 end)
print(L[:3])    # 同上,省略起始
print(L[1:3])   # ['赖庆庆', '周文强']
print(L[-2:])   # ['徐波', '宏'](负索引从右数)
print(L[2:-2])  # ['周文强']

2.2 负索引图解

lua 复制代码
正索引:   0        1        2        3        4
        ------- ------- ------- ------- -------
        | 曹辉 | 赖庆庆 | 周文强 | 徐波  |  宏  |
        ------- ------- ------- ------- -------
负索引:  -5      -4      -3      -2      -1

规则: L[i:j] 包含索引 i,不包含索引 j(左闭右开)

2.3 切片的高级技巧

python 复制代码
L = list(range(100))  # [0,1,2,...,99]

# 1. 步长(每隔几个取一个)
print(L[:10:2])    # [0,2,4,6,8](前10个,步长2)
print(L[::5])      # [0,5,10,15,...](每5个取一个)
print(L[1::2])     # 奇数索引元素

# 2. 反转列表(经典用法)
print(L[::-1])     # [99,98,97,...,0]

# 3. 切片赋值(原地修改)
L[1:4] = ['a','b','c']  # 替换索引1-3
L[1:1] = ['x','y']      # 在索引1位置插入
L[1:3] = []             # 删除索引1-2

# 4. 浅拷贝
copy = L[:]          # 等价于 L.copy()

2.4 切片不止于列表

Python 中一切序列都支持切片

python 复制代码
# 字符串切片
s = 'ABCDEFG'
print(s[:3])      # 'ABC'
print(s[::2])     # 'ACEG'
print(s[::-1])    # 'GFEDCBA'(反转字符串)

# 元组切片
t = (1,2,3,4,5)
print(t[1:4])     # (2,3,4)

# range 切片
r = range(100)
print(r[10:20:2])  # range(10, 20, 2)

2.5 切片的底层原理

python 复制代码
L = [1,2,3,4,5]
slice_obj = slice(1, 4, 2)  # 创建切片对象
print(L[slice_obj])         # [2,4]

# 自定义类支持切片
class MyList:
    def __init__(self, data):
        self.data = data
    
    def __getitem__(self, key):
        if isinstance(key, slice):
            # 处理切片
            return self.data[key.start:key.stop:key.step]
        return self.data[key]
    
    def __setitem__(self, key, value):
        self.data[key] = value

三、实战:手写 trim 函数

3.1 需求分析

python 复制代码
# 目标:实现一个 trim 函数,去掉字符串首尾空格
print(trim("  hello world "))   # "hello world"
print(trim("   "))               # ""(全是空格)
print(trim("no spaces"))         # "no spaces"

# 不允许直接用 s.strip()

3.2 双指针 + 切片实现

python 复制代码
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]

3.3 测试用例

python 复制代码
def test_trim():
    assert trim("  hello world ") == "hello world"
    assert trim("hello world  ") == "hello world"
    assert trim("  hello world") == "hello world"
    assert trim("hello world") == "hello world"
    assert trim("   ") == ""
    assert trim("") == ""
    print("所有测试通过!")

test_trim()

3.4 为什么不用循环拼接?

❌ 差的做法:

python 复制代码
result = ''
for i in range(left, right):
    result += s[i]      # 每次循环创建新字符串,O(n²)

✅ 好的做法:

python 复制代码
return s[left:right]    # 一次性切片,O(n) 且更简洁

知识点: Python 字符串是不可变对象,循环拼接会产生大量临时对象。切片是 C 级别实现,性能更好。


四、跃迁:调用大模型 API

4.1 配置 DeepSeek 客户端

python 复制代码
from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DEEPSEEK_API_KEY"),  # 从环境变量读取
    base_url="https://api.deepseek.com/v1"   # DeepSeek 端点
)

为什么用环境变量?

python 复制代码
# ❌ 危险:API Key 暴露在代码中
api_key = "sk-xxxxx"

# ✅ 安全:通过环境变量读取
api_key = os.getenv("DEEPSEEK_API_KEY")

# 或在命令行设置
# export DEEPSEEK_API_KEY="sk-xxxxx"  (Linux/Mac)
# set DEEPSEEK_API_KEY=sk-xxxxx       (Windows)

4.2 Prompt 设计详解

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_point and 
price_range
"""

Prompt 设计黄金法则:

原则 说明 示例
角色设定 告诉 AI 它是什么角色 "You are an Amazon product listing expert"
任务拆解 把复杂任务分步骤 1.写标题 2.列卖点 3.估价
格式约束 明确输出格式 Output as JSON with fields...
示例引导 给 few-shot 示例 For example: {...}
负面约束 明确不要什么 Do NOT include pricing in title

4.3 调用 Completion 接口

python 复制代码
COMPLETION_MODEL = "deepseek-chat"

def get_response(prompt, temperature=0.7, max_tokens=500):
    response = client.chat.completions.create(
        model=COMPLETION_MODEL,
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},  # 系统提示词
            {"role": "user", "content": prompt}
        ],
        temperature=temperature,   # 0-2,越高越随机
        max_tokens=max_tokens,     # 最大输出长度
        top_p=0.9,                 # 核采样
        frequency_penalty=0.5,     # 重复惩罚
        presence_penalty=0.5       # 主题惩罚
    )
    return response.choices[0].message.content

4.4 参数详解

参数 范围 作用
temperature 0-2 控制随机性。0=确定性输出,2=非常随机
max_tokens 1-4096 最大输出 token 数
top_p 0-1 核采样。0.9 表示只考虑概率总和 90% 的 token
frequency_penalty -2-2 降低重复词的倾向
presence_penalty -2-2 鼓励引入新话题

4.5 输出示例

json 复制代码
{
  "title": "Inflatable PVC Light-Up Frog Toy for Kids - Water Fun Night Light Floating Pool Decor",
  "selling_point": [
    "Eye-catching LED lights make frogs glow in dark",
    "Durable PVC material withstands rough play",
    "Multi-purpose: pool toy, night light, street stall decoration",
    "Lightweight and portable for easy carrying",
    "Affordable price perfect for夜市 vendors"
  ],
  "price_range": "$5.99 - $12.99"
}

五、DeepSeek vs OpenAI vs 其他

5.1 主流 LLM 对比

模型 厂商 特点 价格 上下文
DeepSeek-V3 深度求索 中文友好,极低价 约 $0.14/1M tokens 128K
GPT-4o OpenAI 综合最强 $2.5-10/1M tokens 128K
Claude 3.5 Anthropic 长上下文,代码强 $3-15/1M tokens 200K
Gemini 1.5 Google 超长上下文 $1.25-5/1M tokens 2M
Qwen-Max 阿里 中文最优 约 $2/1M tokens 32K

5.2 API 格式兼容性

python 复制代码
# OpenAI 格式已成为事实标准
# DeepSeek、智谱、阿里都兼容

# 切换模型只需改两个地方:
client = OpenAI(
    api_key="your-key",
    base_url="https://api.deepseek.com/v1"  # 改成对应 URL
)
model = "deepseek-chat"  # 改成对应模型名

5.3 流式输出

python 复制代码
# 实时接收响应(适合聊天应用)
stream = client.chat.completions.create(
    model="deepseek-chat",
    messages=[{"role": "user", "content": "讲个笑话"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end='')

六、代码优化与最佳实践

6.1 异常处理

python 复制代码
def get_response_safe(prompt, max_retries=3):
    for attempt in range(max_retries):
        try:
            response = client.chat.completions.create(
                model="deepseek-chat",
                messages=[{"role": "user", "content": prompt}],
                timeout=30  # 设置超时
            )
            return response.choices[0].message.content
        except Exception as e:
            print(f"Attempt {attempt + 1} failed: {e}")
            if attempt == max_retries - 1:
                raise
            time.sleep(2 ** attempt)  # 指数退避

6.2 解析 JSON 输出

python 复制代码
import json
import re

def extract_json(text):
    """从 LLM 输出中提取 JSON"""
    # 尝试直接解析
    try:
        return json.loads(text)
    except:
        pass
    
    # 匹配 markdown 代码块中的 JSON
    pattern = r'```json\s*(\{.*?\})\s*```'
    match = re.search(pattern, text, re.DOTALL)
    if match:
        return json.loads(match.group(1))
    
    # 匹配裸 JSON 对象
    pattern = r'\{.*\}'
    match = re.search(pattern, text, re.DOTALL)
    if match:
        return json.loads(match.group(0))
    
    raise ValueError("No valid JSON found in response")

6.3 完整的生产级示例

python 复制代码
import os
import json
import time
from openai import OpenAI
from typing import Dict, List, Optional

class AmazonListingGenerator:
    """亚马逊商品文案生成器"""
    
    def __init__(self, api_key: Optional[str] = None):
        self.client = OpenAI(
            api_key=api_key or os.getenv("DEEPSEEK_API_KEY"),
            base_url="https://api.deepseek.com/v1"
        )
        self.model = "deepseek-chat"
    
    def generate_listing(self, product_cn: str) -> Dict:
        """生成完整的亚马逊商品信息"""
        
        prompt = f"""
You are an Amazon product listing expert. 
Generate a complete listing for the following product:

Product: {product_cn}

Requirements:
1. Title: Under 20 words, English, SEO-friendly
2. 5 bullet points: Each under 30 words, feature-benefit focused
3. Price range: Realistic for US market ($)
4. Category: Most relevant Amazon category
5. Keywords: 10 search terms for backend search

Output format (JSON only, no other text):
{{
    "title": "",
    "bullet_points": [],
    "price_range": "",
    "category": "",
    "keywords": []
}}
"""
        response = self._call_api(prompt)
        return self._parse_json(response)
    
    def _call_api(self, prompt: str) -> str:
        response = self.client.chat.completions.create(
            model=self.model,
            messages=[{"role": "user", "content": prompt}],
            temperature=0.7,
            max_tokens=800
        )
        return response.choices[0].message.content
    
    def _parse_json(self, text: str) -> Dict:
        # 提取并解析 JSON
        start = text.find('{')
        end = text.rfind('}') + 1
        return json.loads(text[start:end])

# 使用示例
generator = AmazonListingGenerator()
result = generator.generate_listing(
    "工厂现货PVC充气青蛙夜市地摊热卖充气玩具发光蛙儿童水上玩具"
)
print(json.dumps(result, indent=2, ensure_ascii=False))

七、完整代码

python 复制代码
#!/usr/bin/env python3
"""
从切片到 API - 完整示例
Python 3.8+ required
"""

import os
import json
from openai import OpenAI

# ============ 第一部分:切片练习 ============
def slice_demo():
    L = ["曹辉", "赖庆庆", "周文强", "徐波", "宏"]
    print("切片演示:")
    print(f"L[:3] = {L[:3]}")
    print(f"L[-2:] = {L[-2:]}")
    print(f"L[::2] = {L[::2]}")
    print(f"L[::-1] = {L[::-1]}")


# ============ 第二部分:手写 trim ============
def trim(s: str) -> str:
    """去掉字符串首尾空格(不调用 strip)"""
    left, right = 0, len(s)
    while left < right and s[left] == ' ':
        left += 1
    while right > left and s[right - 1] == ' ':
        right -= 1
    return s[left:right]


def test_trim():
    assert trim("  hello world ") == "hello world"
    assert trim("   ") == ""
    print("trim 测试通过!")


# ============ 第三部分:大模型调用 ============
def create_client():
    """创建 DeepSeek 客户端"""
    api_key = os.getenv("DEEPSEEK_API_KEY")
    if not api_key:
        raise ValueError("请设置环境变量 DEEPSEEK_API_KEY")
    return OpenAI(api_key=api_key, base_url="https://api.deepseek.com/v1")


def generate_product_listing(prompt: str) -> str:
    """生成亚马逊商品文案"""
    client = create_client()
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[{"role": "user", "content": prompt}],
        temperature=0.7,
        max_tokens=500
    )
    return response.choices[0].message.content


# ============ 主程序 ============
if __name__ == "__main__":
    # 1. 切片演示
    slice_demo()
    
    # 2. trim 测试
    test_trim()
    print(f'trim("  hello world ") = "{trim("  hello world ")}"')
    
    # 3. 大模型调用(需要有 API Key)
    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_point and 
price_range
"""
    
    # 如果设置了 API Key 就运行
    if os.getenv("DEEPSEEK_API_KEY"):
        result = generate_product_listing(prompt)
        print("\n大模型输出:")
        print(result)
    else:
        print("\n跳过 API 调用:未设置 DEEPSEEK_API_KEY 环境变量")

八、知识点总结

你从这篇文章学到了:

知识点 要点
List 特性 动态长度、类型自由、有序可改
切片语法 [start:end:step],左闭右开,支持负索引
切片应用 截取、反转、浅拷贝、切片赋值
字符串处理 双指针 + 切片实现 trim
API 调用 OpenAI 格式、参数调优
Prompt 工程 任务拆解、格式约束、示例引导
最佳实践 环境变量、异常处理、JSON 解析

下一步学习建议

  1. 理解生成式 AI 原理:学习 Transformer 架构
  2. 掌握更多 LLM 特性:函数调用、RAG、Agent
  3. 学习 AI 应用框架:LangChain、LlamaIndex
  4. 深入 Python:装饰器、生成器、异步编程

互动时间

你用切片写过最巧妙的代码是什么?

或者你第一次调用大模型 API 时,写的是什么 Prompt?

欢迎评论区分享 👇


本文标签#Python切片 #DeepSeek #大模型开发 #Prompt工程 #API调用 #编程入门

相关推荐
我爱cope2 小时前
【Agent智能体8 | 反思设计模式-大语言模型反思机制的四个演进阶段】
人工智能·设计模式·语言模型
我爱cope3 小时前
【Agent智能体9 | 反思设计模式-提示词工程的进阶法则】
人工智能·设计模式·语言模型·职场和发展
sinat_2554878117 小时前
IDEA:查找文件/类
java·ide·设计模式·intellij-idea
cg.family20 小时前
Java设计模式的七大原则
java·设计模式
deephub21 小时前
Agentic 设计模式拆解:6 种结构的优缺点与应用场景
人工智能·设计模式·大语言模型·多智能体
雪度娃娃21 小时前
行为型设计模式——访问者模式
设计模式·访问者模式
老码观察1 天前
设计模式实战解读(四):观察者模式——事件驱动的解耦利器
观察者模式·设计模式·log4j
我爱cope1 天前
【Agent智能体7 | 智能体设计模式】
人工智能·设计模式
詩飛1 天前
设计模式之建造者模式&模版模式、策略模式
后端·设计模式