当前位置: 首页 > news >正文

【学习笔记】《Python编程 从入门到实践》第3章:Python列表完全指南——创建、修改、删除与排序

第3章 列表简介

本章目标:理解列表的概念,掌握创建、访问、修改、删除列表元素的方法,学会组织列表的常用操作。


3.1 列表是什么

列表 由一系列按特定顺序排列的元素组成。用方括号 [] 表示,逗号分隔元素。

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
# ['trek', 'cannondale', 'redline', 'specialized']

建议给列表指定复数名称,如 lettersdigitsnames

3.1.1 访问列表元素

通过索引(从 0 开始)访问:

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])                 # trek
print(bicycles[0].title())         # Trek(可对元素调用字符串方法)

3.1.2 索引从 0 而不是 1 开始

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[1])     # cannondale(第二个元素)
print(bicycles[3])     # specialized(第四个元素)

负索引:-1 表示最后一个元素

print(bicycles[-1]) # specialized
print(bicycles[-2]) # redline(倒数第二个)
print(bicycles[-3]) # cannondale

3.1.3 使用列表中的各个值

bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = "My first bicycle was a " + bicycles[0].title() + "."
print(message)
# My first bicycle was a Trek.

3.2 修改、添加和删除元素

3.2.1 修改列表元素

直接通过索引赋值:

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles[0] = 'ducati'
print(motorcycles)
# ['ducati', 'yamaha', 'suzuki']

3.2.2 在列表中添加元素

append() — 在末尾添加:

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.append('ducati')
print(motorcycles)
# ['honda', 'yamaha', 'suzuki', 'ducati']

常用模式:先建空列表,再 append

motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)

['honda', 'yamaha', 'suzuki']

insert() — 在任意位置插入(指定索引和值):

motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)
# ['ducati', 'honda', 'yamaha', 'suzuki']

insert(0, 'ducati') 在索引 0 处插入,原有元素右移。

3.2.3 从列表中删除元素

方法用法特点
del del list[index] 删除后无法再访问该值
pop() list.pop() 删除末尾元素并返回该值
pop(index) list.pop(index) 删除任意位置元素并返回
remove() list.remove(value) 按值删除第一个匹配项

del 语句 — 按位置删除(不再需要该值):

motorcycles = ['honda', 'yamaha', 'suzuki']
del motorcycles[0]
print(motorcycles)
# ['yamaha', 'suzuki']

del motorcycles[1]
print(motorcycles)

['honda', 'suzuki']

pop() 方法 — 删除并继续使用该值:

# 默认弹出末尾
motorcycles = ['honda', 'yamaha', 'suzuki']
popped_motorcycle = motorcycles.pop()
print(motorcycles)           # ['honda', 'yamaha']
print(popped_motorcycle)     # suzuki

使用弹出的值

last_owned = motorcycles.pop()
print("The last motorcycle I owned was a " + last_owned.title() + ".")

pop(index) — 弹出任意位置:

motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print('The first motorcycle I owned was a ' + first_owned.title() + '.')
# The first motorcycle I owned was a Honda.

判断标准

  • 删除后不再使用del
  • 删除后还要使用pop()

remove() — 按值删除(只删第一个匹配项):

motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
motorcycles.remove('ducati')
print(motorcycles)
# ['honda', 'yamaha', 'suzuki']

可先用变量存储,删除后继续使用该值

too_expensive = 'ducati'
motorcycles.remove(too_expensive)
print("\nA " + too_expensive.title() + " is too expensive for me.")

A Ducati is too expensive for me.

⚠️ remove() 只删除第一个匹配值。多个重复值需要用循环处理(第 7 章)。


3.3 组织列表

3.3.1 sort() — 永久排序

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)
# ['audi', 'bmw', 'subaru', 'toyota']

倒序排列

cars.sort(reverse=True)
print(cars)

['toyota', 'subaru', 'bmw', 'audi']

sort() 永久修改列表顺序,不可恢复。

3.3.2 sorted() — 临时排序

cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)

print("\nHere is the sorted list:")
print(sorted(cars))

print("\nHere is the original list again:")
print(cars)

倒序临时排序

print(sorted(cars, reverse=True))

sorted() 返回排序后的副本,不修改原列表。

3.3.3 reverse() — 反转列表

cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.reverse()
print(cars)
# ['subaru', 'toyota', 'audi', 'bmw']

reverse() 永久反转顺序,再次调用可恢复。

3.3.4 len() — 获取列表长度

>>> cars = ['bmw', 'audi', 'toyota', 'subaru']
>>> len(cars)
4

3.4 使用列表时避免索引错误

IndexError: list index out of range — 索引超出列表范围:

motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[3])    # ❌ IndexError(只有索引 0, 1, 2)

解决方法

  1. 尝试将索引减 1
  2. 使用 -1 访问最后一个元素(仅在列表非空时有效)
  3. 将列表或其长度打印出来,查看实际内容
# 空列表使用 -1 也会出错
motorcycles = []
print(motorcycles[-1])   # ❌ IndexError

动手试一试

3-1 姓名

names = ['Alice', 'Bob', 'Charlie']
print(names[0])
print(names[1])
print(names[2])

3-2 问候语

names = ['Alice', 'Bob', 'Charlie']
print("Hello, " + names[0] + "!")
print("Hello, " + names[1] + "!")
print("Hello, " + names[2] + "!")

3-3 自己的列表

commute = ['motorcycle', 'car', 'bike']
print("I would like to own a Honda " + commute[0] + ".")

3-4 ~ 3-7 嘉宾名单系列

# 3-4 嘉宾名单
guests = ['Einstein', 'Mozart', 'Curie']
print("Dear " + guests[0] + ", please join me for dinner.")
print("Dear " + guests[1] + ", please join me for dinner.")
print("Dear " + guests[2] + ", please join me for dinner.")

3-5 修改嘉宾名单

print("\n" + guests[1] + " can't make it.")
guests[1] = 'Newton'
print("Dear " + guests[0] + ", please join me for dinner.")
print("Dear " + guests[1] + ", please join me for dinner.")
print("Dear " + guests[2] + ", please join me for dinner.")

3-6 添加嘉宾

print("\nI found a bigger table!")
guests.insert(0, 'Da Vinci')
guests.insert(2, 'Shakespeare')
guests.append('Tesla')
print("Dear " + guests[0] + ", please join me for dinner.")
print("Dear " + guests[1] + ", please join me for dinner.")
print("Dear " + guests[2] + ", please join me for dinner.")
print("Dear " + guests[3] + ", please join me for dinner.")
print("Dear " + guests[4] + ", please join me for dinner.")
print("Dear " + guests[5] + ", please join me for dinner.")

3-7 缩减名单

print("\nSorry, I can only invite two people for dinner.")
popped = guests.pop()
print("Sorry " + popped + ", I can't invite you to dinner.")
popped = guests.pop()
print("Sorry " + popped + ", I can't invite you to dinner.")
popped = guests.pop()
print("Sorry " + popped + ", I can't invite you to dinner.")
popped = guests.pop()
print("Sorry " + popped + ", I can't invite you to dinner.")
print("\nDear " + guests[0] + ", you're still invited.")
print("Dear " + guests[1] + ", you're still invited.")
del guests[0]
del guests[0]
print(guests) # []

3-8 放眼世界

places = ['Tokyo', 'Iceland', 'New Zealand', 'Egypt', 'Brazil']
print(places)
print(sorted(places))
print(places)
print(sorted(places, reverse=True))
print(places)
places.reverse()
print(places)
places.reverse()
print(places)
places.sort()
print(places)
places.sort(reverse=True)
print(places)

3-9 晚餐嘉宾

guests = ['Einstein', 'Mozart', 'Curie', 'Newton', 'Da Vinci']
print("I invited " + str(len(guests)) + " guests to dinner.")

3-10 尝试使用各个函数

languages = ['Python', 'Java', 'C', 'JavaScript', 'Ruby']
print(languages)
print(sorted(languages))
languages.sort()
print(languages)
languages.sort(reverse=True)
print(languages)
languages.reverse()
print(languages)
print(len(languages))
languages.append('Go')
languages.insert(0, 'Swift')
print(languages)
languages.pop()
languages.remove('Swift')
print(languages)

3-11 有意引发错误

items = [1, 2, 3]
# print(items[3])   # ❌ IndexError
print(items[-1])    # ✅ 使用 -1 安全访问最后一个

代码块汇总

# 创建列表
bicycles = ['trek', 'cannondale', 'redline', 'specialized']

访问元素(索引从 0 开始)

bicycles[0] # 第一个元素
bicycles[-1] # 最后一个元素

修改

motorcycles[0] = 'ducati'

添加

motorcycles.append('ducati') # 末尾
motorcycles.insert(0, 'ducati') # 指定位置

删除

del motorcycles[0] # 按索引删除(不使用值)
popped = motorcycles.pop() # 弹出末尾(使用值)
popped = motorcycles.pop(0) # 弹出任意位置
motorcycles.remove('ducati') # 按值删除(只删第一个)

排序

cars.sort() # 永久排序
cars.sort(reverse=True) # 永久倒序
sorted(cars) # 临时排序
sorted(cars, reverse=True) # 临时倒序

反转

cars.reverse()

长度

len(cars)


常见错误 / 陷阱

错误类型说明解决
IndexError 索引超出范围 索引从 0 开始,最大索引为 len(list) - 1
空列表 -1 空列表用 -1 也会出错 访问前检查列表是否为空
remove() 只删一个 重复值只删第一个 用循环处理
误用 sort() 以为 sort() 不影响原列表 sort() 永久修改,sorted() 临时修改

复习要点

  • 列表用 [] 表示,元素用逗号分隔
  • 索引从 0 开始,-1 访问最后一个
  • append() 末尾添加,insert() 任意位置插入
  • del / pop() / remove() 三种删除方式的区别和适用场景
  • sort() 永久排序 vs sorted() 临时排序
  • reverse() 反转列表顺序
  • len() 获取列表长度
  • 避免 IndexError:最大索引 = len(list) - 1

下一章,我们一起去操作操作列表第4章-操作列表

http://www.jsqmd.com/news/892745/

相关文章:

  • 半监督图学习在金融反洗钱中的应用:从图嵌入到模型解释
  • 深圳劳动仲裁服务机构选择参考:多场景下的实操经验 - 资讯速览
  • 多语言仇恨言论检测:从词嵌入到Transformer的混合策略与实战
  • 从频域到电路:DCDC开关电源补偿网络的设计与实战调优
  • 非自伴边值问题的L-Fourier分析:从双正交系统到卷积与分布理论
  • 泰勒展开工程实践:函数近似与局部线性化的实时优化
  • 3分钟掌握跨平台资源下载:res-downloader让你的网络资源收集效率翻倍
  • 2026年6月最新万国官方售后服务中心全指南 | 精准工艺与尊享服务 - 资讯速览
  • LinkSwift网盘直链下载助手:3分钟实现9大网盘下载自由
  • 上海背调公司实测评测:合规性与效率核心维度对比 - 资讯纵览
  • 基于H型梁超表面与特征模分析的双频圆极化天线设计解析
  • 使用 Taotoken CLI 工具一键配置开发环境中的多工具 AI 密钥
  • 机器学习赋能分子动力学增强采样:从数据驱动CV到智能偏置与生成模型
  • 别再踩坑!泰州美甲易起翘 / 伤甲 / 流水线?15 年美业导师揭秘泰州美甲推荐攻略 - 资讯纵览
  • 向量空间JBoltAI v4.4:ReAct推理链走向全透明
  • 大一寸证件照怎么制作?2026大一寸尺寸标准+适用场景+手机教程 - 科技大爆炸
  • 【数字信号去噪】基于matlab人工旅鼠算法优化变分模态分解ALA-VMD数字信号去噪(优化K值 alpha值 综合指标 适应度函数包络熵)【含Matlab源码 15563期】
  • 现在不掌握AI Agent低代码开发,半年后将失去项目主导权:一线CTO紧急发布的48小时速成路径
  • 基于像素级非局部模型的深度图像修复:原理、实现与优化
  • 高学历低能力零基础如何找到Agent开发实习
  • 免系统代理抓包:Chrome插件精准路由HTTPS流量实战
  • 如何解决 AI Agent Harness Engineering 的“幻觉”问题?
  • 基于多尺度视觉Transformer的语音情感识别:从梅尔频谱到MViTv2实战
  • 最美证件照怎么制作?2026让证件照更好看的小技巧 - 科技大爆炸
  • 新国标无机布(A,c类)防火卷帘价格多少钱。仅供参考
  • 别再手动折腾了!用Docker Compose一键部署Yapi接口管理平台(附完整配置文件)
  • 【轨迹跟踪】基于matlab Rovere的滑移引导轨迹跟踪【含Matlab源码 15573期】
  • Windows远程桌面CredSSP加密Oracle修正错误修复指南
  • 基于交叉注意力的可解释AI:照亮帕金森病语音诊断黑盒模型
  • 通过curl命令直接测试Taotoken大模型API接口的简易方法