Python列表常用操作方法

Python列表(list)是最常用的数据结构之一,以下是列表的常用操作方法:

1. 创建列表

python 复制代码
empty_list = []  # 空列表
numbers = [1, 2, 3, 4, 5]  # 数字列表
mixed = [1, "hello", 3.14, True]  # 混合类型列表
nested = [[1, 2], [3, 4]]  # 嵌套列表

2. 访问元素

python 复制代码
my_list = ['a', 'b', 'c', 'd', 'e']

print(my_list[0])  # 'a' - 第一个元素
print(my_list[-1])  # 'e' - 最后一个元素
print(my_list[1:3])  # ['b', 'c'] - 切片 左闭右开则,含头不含尾

3. 修改列表

python 复制代码
my_list = [1, 2, 3]

my_list[0] = 10  # 修改元素 [10, 2, 3]
my_list.append(4)  # 末尾添加 [10, 2, 3, 4]
my_list.insert(1, 5)  # 在索引1处插入5 [10, 5, 2, 3, 4]

4. 删除元素

python 复制代码
my_list = ['a', 'b', 'c', 'd']

del my_list[0]  # 删除索引0的元素 ['b', 'c', 'd']
my_list.remove('c')  # 删除第一个出现的'c' ['b', 'd']
popped = my_list.pop()  # 删除并返回最后一个元素 'd', 列表变为 ['b']

5. 列表操作

python 复制代码
list1 = [1, 2]
list2 = [3, 4]

combined = list1 + list2  # [1, 2, 3, 4] - 连接
repeated = list1 * 3  # [1, 2, 1, 2, 1, 2] - 重复

6. 常用方法

python 复制代码
nums = [1, 2, 3, 4]

nums.extend([5, 6])  # 扩展列表 [1, 2, 3, 4, 5, 6]
nums.index(3)  # 返回3的索引 2
nums.count(2)  # 返回2出现的次数 1
nums.reverse()  # 反转列表 [6, 5, 4, 3, 2, 1]
nums.sort()  # 排序 [1, 2, 3, 4, 5, 6]
nums.copy()  # 浅拷贝
nums.clear()  # 清空列表 []

7. 列表推导式

python 复制代码
squares = [x**2 for x in range(10)]  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 1-10所有数的2次方
evens = [x for x in range(10) if x % 2 == 0]  # [0, 2, 4, 6, 8] 1-10所有数的偶数

8. 其他操作

python 复制代码
len([1, 2, 3])  # 3 - 长度
3 in [1, 2, 3]  # True - 成员检查
max([1, 2, 3])  # 3 - 最大值
min([1, 2, 3])  # 1 - 最小值
sum([1, 2, 3])  # 6 - 求和

这些是Python列表最常用的操作方法,掌握它们可以高效地处理各种列表操作任务。

相关推荐
AI攻城狮3 小时前
用 Playwright 实现博客一键发布到稀土掘金
python·自动化运维
曲幽3 小时前
FastAPI分布式系统实战:拆解分布式系统中常见问题及解决方案
redis·python·fastapi·web·httpx·lock·asyncio
孟健18 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞20 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽1 天前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python