【笔记-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]
相关推荐
用户7088769039383 小时前
给传统 SaaS 增加 AI 能力:3个真实落地场景
python
卷无止境3 小时前
FastAPI中间件全解析:请求处理链条上的隐形关卡
后端·python·fastapi
用户0332126663673 小时前
使用 Python 将 HTML 内容添加到 PowerPoint 演示文稿中
python·html
GlueNa2SiO33 小时前
07-Docker Compose多容器编排
笔记·学习·docker·容器
看浪的路人3 小时前
第4讲:MCP Client 开发——连接、发现、调用
windows·python·ai
Lazionr3 小时前
list容器详解——双向链表的封装与使用
数据结构·c++·链表·list
Swift社区3 小时前
Python 开发环境怎么选?PyCharm、VS Code、Trae 谁更适合 AI 开发?
人工智能·python·pycharm
卷无止境3 小时前
聊聊Web开发里的流式数据 从原理到FastAPI实战
后端·python·fastapi
SMF19193 小时前
【PyCharm】让 PyCharm 使用 .venv 虚拟环境
ide·python·pycharm
修远客3 小时前
感知模块:Agent的眼睛和耳朵 — 三层降级策略让Agent永不"失明"
python·agent