Python学习笔记:List切片与LLM接口实战

11 阅读4分钟

Python学习笔记:List切片与LLM接口实战

最近学习了一点Python,顺手整理了一份Jupyter Notebook笔记,记录了列表(list)的基本操作、切片的高级用法,以及如何调用大语言模型接口生成产品文案。下面分享给大家。

一、Python中的列表

Python中没有Java/C++那种内置的定长数组,而是提供了灵活、有序、可修改的列表(list)。它的特点很实用:

  • 长度可变,不需要提前指定容量(类似JavaScript中的数组)
  • 不约束元素类型,同一个列表里可以放字符串、数字、甚至其他列表

python

# 定义一个包含5个名字的列表
L = ["张三", "李四", "王五", "赵六", "孙七"]

# 取前三项,可以用索引逐个获取
[L[0], L[1], L[2]]

当然也有更优雅的做法——用一个循环把前n个元素追加到新列表里:

python

r = []
n = 3
for i in range(n):
    r.append(L[i])
r   # 输出 ['张三', '李四', '王五']

人生苦短,我用Python —— 其实有更简洁的写法,那就是切片。

二、切片操作

切片(slice)可以大大简化取子集的操作,语法是 [start:stop:step]

基本用法

python

L[0:3]   # 从索引02,输出 ['张三','李四','王五']
L[:3]    # 省略起始索引,效果同上
L[1:3]   # 从索引12,输出 ['李四','王五']
L[-2:]   # 最后两项,输出 ['赵六','孙七']

带步长的切片

当列表元素很多时,步长参数非常有用:

python

L = list(range(100))   # 生成0..99的列表

L[:10]        # 前10个: [0,1,2,...,9]
L[-10:]       # 后10个: [90,91,...,99]
L[:10:2]      # 前10个中每2个取一个: [0,2,4,6,8]
L[::5]        # 每5个取一个: [0,5,10,...,95]

字符串也是序列

字符串同样支持切片操作:

python

'ABCDEFG'[:3]    # 'ABC'
'ABCDEFG'[::2]   # 'ACEG'

三、动手实现trim函数

Python字符串自带strip()方法可以去掉首尾空格,但如果想自己实现,可以借助切片和双指针:

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]

print(trim("   hello world "))   # 输出 'hello world'

思路很简单:从左边找到第一个非空格位置,从右边找到最后一个非空格位置,最后用切片截取中间部分。

四、调用LLM接口生成产品文案

有了Python的基础操作,我们还可以做点有意思的事 —— 调用大语言模型接口。下面以DeepSeek为例(兼容OpenAI的Python SDK),根据中文产品描述生成亚马逊(Amazon)上的英文产品标题、卖点和价格区间。

1. 初始化客户端

python

from openai import OpenAI

client = OpenAI(
    api_key="sk-665d3142ca9d480c9c6823c67f0cbe00",
    base_url="https://api.deepseek.com/v1"
)

COMPLETION_MODEL = "deepseek-chat"

2. 编写Prompt

Prompt的关键是清晰、分步骤,并约束输出为JSON格式:

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
"""

3. 调用接口并打印结果

python

def get_response(prompt):
    response = client.chat.completions.create(
        model = COMPLETION_MODEL,
        messages= [
            { "role":"user", "content": prompt }
        ]
    ) 
    return response.choices[0].message.content

print(get_response(prompt))

运行后,模型返回了类似下面的JSON:

json

{
  "title": "Glow-in-the-Dark PVC Inflatable Frog Toy for Night Market, Water Play & Party Fun",
  "selling_points": [
    "Bright LED light-up design makes it glow in the dark for extra fun at night",
    "Durable PVC material resists punctures and is perfect for water or land play",
    "Easy to inflate and deflate for quick setup and convenient storage",
    "Lightweight and portable, ideal for夜市 (night markets), beaches, and pools",
    "Great for kids' outdoor activities, party favors, and interactive water toys"
  ],
  "price_range": "$9.99 – $14.99"
}

这样,我们就用几行代码完成了一次“产品文案自动生成”的小实验。

总结

以上是这次notebook里的全部内容:从Python列表的基本特性,到灵活强大的切片操作,再到自己实现一个trim函数,最后调用LLM接口完成实际任务。Notebook这种边写代码边记录的方式非常适合学习和数据分析,推荐大家也试试。