Python List、切片与大模型:从入门到实践的优雅之旅

前言

大家好!今天我们来聊聊 Python 开发中几个非常实用的知识点------Python List、切片操作,以及如何将这些基础操作在大模型时代的实际应用。这篇文章将带你从基础概念走到实战,保证干货满满,看完就能用!


一、Python List:灵活的通用容器

1.1 List 是什么?

Python 中最灵活的特性之一就是 List,它不像 Java/C++ 那样需要提前指定容量和类型,和 JS 的 Array 类似,但更加优雅。可以说,JS 借鉴了 Python 的很多特性,不过两者真是一对好兄弟。

python 复制代码
# Python 中本身没有 Java/C++ 那样的内置数组
# list 是 Python 中灵活有序、可修改的通用容器列表
L = ["曹辉", 500, "赖庆庆", "周文强", "徐波", "洪忠圣"]
print(L)  # ['曹辉', 500, '赖庆庆']

1.2 Python vs JavaScript:各有所长

  • Python:适合机器学习、爬虫、数据分析
  • JavaScript:Number 类型没有高精度浮点数类型,特别适合做页面展示和交互

二、切片 Slice:人生苦短,我用 Python

2.1 切片简化了取元素的操作

切片是 Python 中大大简化了取元素的操作,让代码更加优雅。

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

# 传统方式取前三项
r = []
n = 3
for i in range(n):
    r.append(L[i])
print(r)  # ['曹辉', 500, '赖庆庆']

# 使用切片
print(L[0:3])   # ['曹辉', 500, '赖庆庆']
print(L[:3])     # 同上,0可以省略
print(L[1:3])   # ['500, '赖庆庆']
print(L[-2:])    # ['徐波', '洪忠圣']

2.2 更多切片技巧

python 复制代码
L = list(range(100))
print(L[-10:])  # 取最后10个元素

# 字符串也可以切片
print('ABCDEFG'[:3])    # 'ABC'
print('ABCDEFG'[::2])  # 'ACEG' 每隔2个取一个

2.3 实战:不使用 strip 的 trim 函数

利用切片实现 trim 函数,这是一个经典的面试题!

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'

三、大模型时代:Transformer 与 LLM 接口

3.1 Transformer 架构:改变世界的架构

  • OpenAI 基于 Google 开源的 Transformer 架构,引领了 2022 年底的生成式人工智能浪潮,现已成为业内标准。

主流 LLM 厂商:

  • OpenAI
  • DeepSeek(兼容 OpenAI 接口)
  • Google Gemini
  • Anthropic Claude

3.2 ModelScope:阿里的开源模型社区

  • ModelScope 是阿里云推出的开源模型社区
  • 包含海量开源模型和数据集
  • 非常适合做 NLP 实验

3.3 实战:调用 DeepSeek API

让我们看看如何使用 DeepSeek API 来处理实际问题:

python 复制代码
from openai import OpenAI

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

COMPLETION_MODEL = "deepseek-chat"
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
"""

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

3.4 Prompt 工程的艺术

写好 Prompt 是用好 LLM 的关键:

  1. **清晰且详细地表达目标(参考 Amazon 的细化方式)
  2. 分步骤:1, 2, 3...
  3. 约束返回格式:指定 JSON 格式,字段名清晰指定

这样 LLM 返回的结果示例:

json 复制代码
{
  "title": "Glow-in-the-Dark Inflatable PVC Frog Toy for Kids, Night Market, Water Play & Pool Fun",
  "selling_point": [
    "Vibrant Glow Feature: Built-in LED lights make this frog shine brightly at night, perfect for evening markets, camping, or backyard fun.",
    "Durable PVC Material: Made from thick, high-quality PVC that resists punctures and withstands rough play, both in water and on land.",
    "Versatile Use: Ideal for swimming pools, bathtubs, beaches, and night markets---a multi-purpose toy that kids love day or night.",
    "Safe & Child-Friendly: BPA-free, non-toxic material with smooth edges ensures safe play for children ages 3 and up.",
    "Attractive Novelty Design: Eye-catching frog shape with bright colors that appeal to kids and easily draw attention at street stalls or retail displays."
  ],
  "price_range": "$9.99 - $15.99"
}

四、Jupyter Notebook:边写代码边记录的神器

Jupyter Notebook 是数据分析、学习和写报告的绝佳工具:

  • 支持 Markdown 文件(.md)
  • Notebook 文件(.ipynb)
  • 边写代码边记录,所见即所得

总结

今天我们从 Python List 的灵活特性,谈到了切片的优雅使用,再到大模型时代的 LLM 接口调用。这些知识点看似简单,但组合起来就能发挥巨大的威力。希望这篇文章对你有所帮助,欢迎在评论区交流!


关键词:Python List、切片、Transformer、LLM、DeepSeek、ModelScope、Prompt 工程

相关推荐
壹米饭11 分钟前
手搓 MCP 到最简 Agent,我都做了什么?
agent·ai编程·mcp
Sakura_j_h_23 分钟前
从零写一个 MCP stdio Server:用 Python 校验博客文章格式
开发语言·python·自动化·ai工具·mcp·json-rpc
大草原的小灰灰31 分钟前
LLM应用的标准开发框架LangChain(八)- 中间件
python·中间件·langchain
无懈可击32 分钟前
Vue 可视化AI表单设计器 FcDesigner v3.6 版本发布,支持导出 SQL功能!
vue.js·开源·ai编程
ZzT38 分钟前
vibe coding 做小游戏·玩法重做篇:只留自走棋、去掉羁绊,用电脑自动对局调难度
ai编程·游戏开发
卷无止境42 分钟前
百万 token 时代的真相:主流大模型上下文窗口与最大输出的横向对比分析
人工智能·python
灵感__idea43 分钟前
Claude Code 实战:AI这么强了,为什么还在发明新概念?
aigc·ai编程·claude
Carson带你学Android1 小时前
AI时代,你的 App 会被 Agent 这三种方式调用
android·ai编程
装不满的克莱因瓶1 小时前
【SpringAI Alibaba】ReactAgent记忆管理MessageTrimmingHook与MessageDeletionHook
java·人工智能·ai·ai编程·springai·springaialibaba
用户298698530141 小时前
Python 实战:将 HTML 批量转换为 Markdown
python·html·markdown