Python容器的类型(List)
·
Python 列表(List)操作详解笔记
基于实际代码示例整理,涵盖列表的创建、访问、增删改查、统计等核心操作,并附带实用拓展知识。
一、列表基础特性
- 有序:元素按插入顺序存储,支持索引访问
- 可变(Mutable):内容可修改
- 异构:可混合不同类型(字符串、整数、布尔值等)
- 支持嵌套:列表中可包含其他列表(实现多维结构)
二、创建列表
1. 直接定义(字面量)
name_list = ['a', 123, True]
print(name_list) # ['a', 123, True]
print(type(name_list)) # <class 'list'>
2. 嵌套列表(二维列表)
name_list = [['d', 123], [True, 456]]
print(name_list) # [['d', 123], [True, 456]]
💡 拓展:可继续嵌套形成三维、四维列表,如
[[[1,2]], [[3,4]]]
三、访问元素:索引与嵌套索引
1. 正向 & 反向索引
name_list = ['a', 'b', 'c']
print(name_list[0]) # 'a'(正向:0 起始)
print(name_list[-1]) # 'c'(反向:-1 起始)
| 索引 | 0 | 1 | 2 |
|---|---|---|---|
| 值 | a | b | c |
| 反向 | -3 | -2 | -1 |
2. 嵌套列表索引
name_list = [['a','b','c'], ['e','f','g']]
print(name_list[0][1]) # 'b' → 第0个子列表的第1个元素
print(name_list[1]) # ['e', 'f', 'g'] → 整个子列表
⚠️ 注意:若索引越界(如
name_list[5]),会抛出IndexError
四、查询元素:.index()
name_list = ['a', 'b', 'c']
index = name_list.index("a")
print(f"a在列表中的下标索引值为: {index}") # a在列表中的下标索引值为: 0
⚠️ 陷阱:
- 若元素不存在,会抛出
ValueError- 只返回第一个匹配项的索引
✅ 安全写法(推荐):
if "x" in name_list:
idx = name_list.index("x")
else:
print("元素不存在")
五、修改元素
name_list = ['a', 'b', 'c']
name_list[1] = "d" # 将索引1的值改为 "d"
print(name_list) # ['a', 'd', 'c']
✅ 支持通过切片批量修改:
name_list[1:3] = ['x', 'y'] # ['a', 'x', 'y']
六、添加元素
| 方法 | 语法 | 特点 |
|---|---|---|
insert() | list.insert(index, item) | 在指定位置插入 |
append() | list.append(item) | 在末尾添加单个元素 |
extend() | list.extend(iterable) | 在末尾添加多个元素(展开 iterable) |
示例:
name_list = ['a', 'b', 'c']
name_list.insert(1, "f") # ['a', 'f', 'b', 'c']
name_list.append("e") # ['a', 'f', 'b', 'c', 'e']
name_list.extend(['q','w']) # ['a', 'f', 'b', 'c', 'e', 'q', 'w']
# 或
name_list2 = ['q','w','e']
name_list.extend(name_list2) # 合并另一个列表
💡 对比:
append(['x','y'])→ 添加一个列表元素:[..., ['x','y']]extend(['x','y'])→ 添加两个字符串元素:[..., 'x', 'y']
七、删除元素
1. del 语句(按索引删除)
name_list = ['a','b','c']
del name_list[0] # 删除索引0的元素
print(name_list) # ['b', 'c']
2. .pop()(删除并返回元素)
name_list = ['a','b','c']
element = name_list.pop(0) # 删除索引0,并返回 'a'
print(name_list) # ['b', 'c']
print(element) # 'a'
# 默认 pop() 删除最后一个
last = name_list.pop() # 删除 'c'
3. .remove()(按值删除)
name_list = ['a','b','c','a']
name_list.remove("a") # 只删除**第一个** 'a'
print(name_list) # ['b', 'c', 'a']
⚠️ 注意:
.remove()若值不存在,会报ValueError
4. .clear()(清空整个列表)
name_list = ['a','b','c']
name_list.clear()
print(name_list) # []
八、统计功能
1. 统计某元素出现次数:.count()
name_list = ['a','b','c','b','c','c']
print(name_list.count("c")) # 3
print(name_list.count("b")) # 2
print(name_list.count("a")) # 1
2. 统计列表总长度:len()
name_list = ['a','b','c']
print(len(name_list)) # 3
九、拓展:实用技巧与注意事项
✅ 1. 判断元素是否存在
if "a" in name_list:
print("存在")
✅ 2. 遍历列表(推荐方式)
# 仅值
for item in name_list:
print(item)
# 值 + 索引
for i, item in enumerate(name_list):
print(f"{i}: {item}")
你提供的这段 Python 代码使用了 enumerate() 函数来遍历一个名为 name_list 的列表,并打印出每个元素的索引和对应的值。这是一个非常常见的用法。
代码解释:
for i, item in enumerate(name_list):
print(f"{i}: {item}")
enumerate(name_list)会返回一个可迭代对象,其中每个元素是一个(索引, 值)的元组。i是当前元素的索引(从 0 开始)。item是name_list中对应位置的元素。- 使用 f-string 格式化输出:
"{i}: {item}"。
示例运行:
假设:
name_list = ["Alice", "Bob", "Charlie"]
运行你的代码会输出:
0: Alice
1: Bob
2: Charlie
小提示:
如果你希望索引从 1 开始,可以这样写:
for i, item in enumerate(name_list, start=1):
print(f"{i}: {item}")
输出:
1: Alice
2: Bob
3: Charlie
⚠️ 3. 避免在遍历时直接修改列表
# ❌ 危险:可能导致跳过元素
for item in name_list:
if item == 'a':
name_list.remove(item)
# ✅ 安全做法:遍历副本
for item in name_list.copy():
if item == 'a':
name_list.remove(item)
✅ 4. 列表复制(避免引用问题)
original = [1, 2, 3]
copy1 = original.copy() # 推荐
copy2 = list(original) # 推荐
copy3 = original[:] # 推荐(切片)
# ❌ 错误:只是创建新引用
copy_bad = original # 修改 copy_bad 会同时改 original!
十、速查表
| 操作 | 方法/语法 |
|---|---|
| 创建 | [] 或 list() |
| 访问 | list[i], list[i][j](嵌套) |
| 查询索引 | list.index(value) |
| 修改 | list[i] = new_value |
| 插入 | insert(i, x) |
| 末尾添加 | append(x) |
| 批量添加 | extend(iterable) |
| 删除(索引) | del list[i] 或 pop(i) |
| 删除(值) | remove(value) |
| 清空 | clear() |
| 统计次数 | count(value) |
| 长度 | len(list) |
💡 口诀:
“列表创建用方括号,索引访问正负都可;
增用 insert/append/extend,删有 del/pop/remove;
查索引用 index,统计 count 和 len!”
更多推荐
所有评论(0)