【笔记-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]
相关推荐
软萌萌的113 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Dxy123931021614 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
持敬chijing15 小时前
Python概述
开发语言·python
赤羽尾风17 小时前
NumPy快速入门
python·numpy
倒流时光三十年17 小时前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django
久久学姐19 小时前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm
Zane199419 小时前
闭包到底"闭"住了什么?一文讲透 LEGB 规则与循环里的闭包陷阱
后端·python
Lumi_Peak20 小时前
Claude思考了42秒,我的代码质量直接提升了一个档次
python·claude
m沐沐20 小时前
【机器学习】DBSCAN聚类算法——原理、参数调优与实战
人工智能·python·深度学习·算法·机器学习·聚类·dbscan