python学习笔记—15—数据容器之列表

  1. 数据容器

列表(list)、元组(tuple)、字符串(str)、集合(set)、字典(dict)

  1. 列表

(1) 定义

python 复制代码
tmp_list = ["super", "carry", "doinb"]
print(f"tmp_list = {tmp_list}, tmp_list type is {type(tmp_list)}")
tmp_list1 = ["doinb", 1, 6.6666]
print(f"tmp_list1 = {tmp_list1}, tmp_list1 type is {type(tmp_list1)}")
tmp_list2 = ["doinb", tmp_list, tmp_list1, ["1", "supercarrydoinb"]]
print(f"tmp_list2 = {tmp_list2}, tmp_list2 type is {type(tmp_list2)}")

(2) 列表下标索引

  1. 正向(从左向右 0 1 2...)
  1. 反向(从右向左 -1 -2 -3...)
  1. 嵌套------列表[子列表][子列表下标]

(3) 方法------定义在类class中的函数称为方法

(4) 列表的常用操作(方法)

  1. index------查询元素在列表中从左到右第一次出现的位置
python 复制代码
tmp_list = ["super", "carry", "doinb", "sdad", "doinb"]
tmp_index = tmp_list.index("doinb")
print(f"doinb 在列表中的元素位置为:{tmp_index}")
  1. 修改特定下标位置的值
python 复制代码
tmp_list = ["super", "carry", "doinb", "sdad", "doinb"]
print(tmp_list)
tmp_list[2] = "nb"
print(tmp_list)
  1. insert------在列表指定下标中插入指定元素
  1. append------在列表尾部追加元素,既能追加元素也能追加其他数据容器(嵌套追加)
  1. extend------取出其他数据容器中的值,追加到本容器中

注意:extend与append区别是后者不涉及嵌套,前者是嵌套追加

  1. del------根据列表下标删除列表元素
  1. pop------将列表中的元素取出并返回取出的元素
  1. remove------删除在列表中从左到右寻找到的第一个 元素
  1. clear------清空整个列表
  1. count------统计某元素在列表中的个数
  1. len------统计列表中的元素个数

(5) 列表的特点

(6) 练习

python 复制代码
tmp_list = [21, 25, 21, 23, 22, 20]
print(tmp_list)
tmp_list.append(31)
print(tmp_list)
tmp_list.extend([29, 33, 30])
print(tmp_list)
tmp = tmp_list.pop(0)
print(tmp_list)
tmp = tmp_list.pop(-1)
print(tmp_list)
tmp = tmp_list.index(31)
print(tmp)

(7) while循环遍历打印列表

python 复制代码
tmp_list = [21, 25, 21, 23, 22, 20]
cnt = 0
while cnt < len(tmp_list):
    print(f"{tmp_list[cnt]} ", end='')
    cnt += 1

(8) for循环遍历列表

python 复制代码
tmp_list = [21, 25, 21, 23, 22, 20]
for i in tmp_list:
    print(f"{i} ", end='')
相关推荐
smppbzyc5 分钟前
2025年亚太杯(中文赛项)数学建模B题【疾病的预测与大数据分析】原创论文讲解(含完整python代码)
python·数学建模·数据分析·数学建模竞赛·亚太杯数学建模·亚太杯
hi0_610 分钟前
03 数组 VS 链表
java·数据结构·c++·笔记·算法·链表
xiaocainiao88117 分钟前
Python 实战:构建可扩展的命令行插件引擎
开发语言·python
运器1231 小时前
【一起来学AI大模型】PyTorch DataLoader 实战指南
大数据·人工智能·pytorch·python·深度学习·ai·ai编程
音元系统1 小时前
Copilot 在 VS Code 中的免费替代方案
python·github·copilot
超龄超能程序猿2 小时前
(5)机器学习小白入门 YOLOv:数据需求与图像不足应对策略
人工智能·python·机器学习·numpy·pandas·scipy
Wy. Lsy2 小时前
Kotlin基础学习记录
开发语言·学习·kotlin
The_Killer.2 小时前
格密码--数学基础--06对偶空间与对偶格
学习·线性代数·密码学
Andy杨2 小时前
20250712-1-Kubernetes 监控与日志管理-K8s日志管理与维护_笔记
笔记·容器·kubernetes
撰卢2 小时前
【个人笔记】负载均衡
运维·笔记·负载均衡