【笔记-Python】内置容器-list

list为python内置容器,其特点:可变、成员有序;

常用操作

创建list
复制代码
# 使用字面量创建list
numbers = [0,1,2,3]

# 使用内置函数list(iterable)将可迭代对象转换为列表
characters = list('hello world!')
遍历list
复制代码
characters = list('hello world!')
# 仅遍历元素
for character in characters:
    print(character)

# enumerate()适用于任何"可迭代对象",接收一个可选参数start用于指定循环下标初始值(默认为0)
# 遍历过程中获取下标
for index,character in enumerate(characters):
    print(index, character)

# 从指定下标开始遍历
for index,character in enumerate(characters, start=1):
    print(index, character)
删除成员
复制代码
characters = list('hello world!')
# 删除list第1个成员
del characters[1]

# 删除list一段成员
del characters[1:]
list推导式
复制代码
numbers = [1,2,3,4,5,6]
# 遍历numbers列表: for number in numbers
# 进行成员过滤: if number%2==1
# 对成员进行操作: number+10
# 构建新的list
results = [number+10 for number in numbers if number%2==1]
相关推荐
Lupino3 小时前
别再只聊 AI 写代码了:技术负责人要把“变更治理”提到第一优先级
python·docker·容器
Flittly4 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(6)Context Compact (上下文压缩)
python·agent
曲幽15 小时前
FastAPI + PostgreSQL 实战:从入门到不踩坑,一次讲透
python·sql·postgresql·fastapi·web·postgres·db·asyncpg
用户83562907805120 小时前
使用 C# 在 Excel 中创建数据透视表
后端·python
码路飞1 天前
FastMCP 实战:一个 .py 文件,给 Claude Code 装上 3 个超实用工具
python·ai编程·mcp
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(2) Evaluator-Optimizer模式
python·langchain
前端付豪1 天前
AI 数学辅导老师项目构想和初始化
前端·后端·python
用户0332126663671 天前
将 PDF 文档转换为图片【Python 教程】
python
悟空爬虫1 天前
UV实战教程,我啥要从Anaconda切换到uv来管理包?
python
dev派1 天前
AI Agent 系统中的常用 Workflow 模式(1)
python·langchain