更多内容请点击下面链接,关注一下微信公众号:
一、简介
数据容器:可以存储多个元素的Python数据类型。比如:字符串、数字、日期类型等。
常见容器如下:
str(字符串),tuple(元组或数组),list(列表),set(集合),dict(字典)
二、常用容器详细介绍
2.1、list(列表)
定义语法:[元素1,元素2,元素3......]
数据类型没有任何限制,甚至元素也可以是列表,也即是可嵌套列表。
#list列表
m_list=[1,"你好",True,1.23];
print("列表中的元素:",m_list);
print("m_list的类型:",type(m_list));
#列表嵌套
m_list02=[[1,2,3,4],[3,3,4,4,5]];
print("列表中的元素:",m_list02);
print("m_list的类型:",type(m_list02));
输出结果:
1、使用下标索引获取列表中的元素
下标索引:列表中每个元素的编号,从前往后编号从0开始递增,从后往前编号为-1开始递减。
取出方式:列表[下标]。
注意事项:超出下标索引的取值范围会报错。
参考案例:
#list列表
m_list=[1,"你好",True,1.23];
print("列表中的元素:",m_list);
print("m_list的类型:",type(m_list));
#列表嵌套
m_list02=[[1,2,3,4],[3,3,4,4,5]];
print("列表中的元素:",m_list02);
print("m_list02的类型:",type(m_list02));
print("m_list列表中的第一个元素:",m_list[0]);
print("m_list列表中的第二个元素:",m_list[1]);
print("m_list列表中的第三个元素:",m_list[2]);
print("m_list02列表中的第一个列表中的第一个元素:",m_list02[0][0]);
print("m_list02列表中的第二个列表中的第三个元素:",m_list02[1][2]);
输出结果:
2、列表中常用的方法
使用参考案例:
#列表中常用方法
m_list=[1,"你好",True,1.23];
m_list2=[4,"小李"];
##一、增加操作
#1、列表中追加一个元素
m_list.append(3);
##追加后的列表m_list中元素:[1, '你好', True, 1.23, 3]
print(f"追加后的列表m_list中元素:{m_list}");
#2、继承容器的方式追加
m_list.extend(m_list2);
##继承后的列表m_list中元素:[1, '你好', True, 1.23, 3, 4, '小李']
print(f"继承后的列表m_list中元素:{m_list}");
#3、指定下标的方式插入元素
m_list.insert(1,"张三");
##插入后的列表m_list中元素:[1, '张三', '你好', True, 1.23, 3, 4, '小李']
print(f"插入后的列表m_list中元素:{m_list}");
##二、删除操作
#2.1、del 删除指定下标下的元素 高版本已废弃
#2.2、pop删除指定下标元素,并返回删除的元素
m_list03=m_list.pop(1);
#pop删除指定下标1元素:张三后的列表:m_list中元素:[1, '你好', True, 1.23, 3, 4, '小李']
print(f"pop删除指定下标1元素:{m_list03}后的列表:m_list中元素:{m_list}");
#2.3、从前往后删除第一个匹配上的元素remove删除
m_list.insert(1,3);
#添加后的元素:[1, 3, '你好', True, 1.23, 3, 4, '小李']
print(f"添加后的元素:{m_list}");
m_list.remove(3);
#remove后的列表m_list中元素:[1, '你好', True, 1.23, 3, 4, '小李']
print(f"remove后的列表m_list中元素:{m_list}");
#2.4、clear清空列表
m_list.clear();
#clear清空列表后的元素:[]
print(f"clear清空列表后的元素:{m_list}");
##三、修改操作
m_list=[1,"你好",True,1.23];
m_list[1]="张三";
#修改列表后的元素:[1, '张三', True, 1.23]
print(f"修改列表后的元素:{m_list}");
##四、查询操作
#4.1、count 统计某个元素出现的次数
nums=m_list.count(1.23);
#列表中1出现的次数:1
print(f"列表中1.23出现的次数:{nums}");
#4.2、容器内有多少元素
lens=len(m_list);
#容器内有多少元素:4
print(f"容器内有多少元素:{lens}");
#4.3、获取指定元素的下标
num=m_list.index(1);
#获取指定元素1的下标:0
print(f"获取指定元素1的下标:{num}");
3、列表(list)的循环遍历
3.1、使用while循环
定义如下:利用下标获取元素
index=0; #定义初始下标
while index < len(列表)
元素=列表[index];
对元素进行处理;
index+=1; #对下标加1
参考案例如下:
#列表的循环遍历
m_list=[1,"你好",True,1.23];
##1、使用while
def while_list_fun(m_list):
index=0;
while index<len(m_list):
print(f"获取指下标{index}对应的元素:{m_list[index]}");
index+=1;
#调用函数
while_list_fun(m_list);
输出结果如下:
3.2、使用for循环
定义如下:依次直接取元素并赋值到临时变量上。
for 临时变量 in list列表:
对临时变量进行处理;
参考案例如下:
def for_list_fun(m_list):
for elmt in m_list:
print(f"获取对应的元素:{elmt}");
#调用函数
#while_list_fun(m_list);
for_list_fun(m_list);
输出结果:
3.3、while与for循环对比
1、while可以自定义循环条件,并自行控制,for不行;
2、while可以无限循环;
3、while循环使用任何想要循环的场景下,for遍历数据容器或简单的固定次数循环,一般常用for循环。
4、for更加简单,while更加灵活。
更多优秀文章,请扫码关注个人微信公众号或搜索“程序猿小杨”添加。