python容器详解之列表
1. 概念:变量只能存储单个数据。容器是存储大量数据的一种数据结构。
2. python容器类型:列表、集合、元组、字典。
3. 列表:list,链表、数组、栈、队列。基于双链表实现。
4 列表的创建:
#方式一:
ls = [1,2,4]
#方式二,全局函数list():
ls = list([1,2,3])
5. 遍历列表元素:
ls = list([1,2,3])
for i in ls:
print(i)
6. 通过下标访问列表的元素:
ls = list([1,2,3])
index = 0
#len()获取列表的长度
while index < len(ls):
print(ls[index])
index +=1
7. 常用的列表方法:
dir(list)查看列表所有的方法
append() 在列表的尾部添加元素
insert(index,object) 在指定的位置添加元素
ls = list([1,2,3])
#在列表下标为2的位置添加一个字符串hello
ls.insert(2,"hello")
sort() 将元素进行排序,int型默认从小到大,其余按照ASCLL码值大小进行排序
index() 查看列表元素的下标
reverse() 反转列表的元素
remove() 通过元素在列表中删除元素
ls = list([1,2,3])
##删除元素2
ls.remove(2)
count() 统计元素在列表中出现的次数
clear() 清除列表
copy 浅拷贝
ls = list([1,2,3])
ls1= list([4,5,6])
#将列表ls1中的元素浅拷贝到列ls中
ls = ls1.copy()
extend() 合并列表
pop() 从列表的尾部删除一个元素,并返回该元素
8.列表中可以嵌套列表:
ls = list([1,2,[3,5]])
#将元素[3,5]中的3输出
print(list[2][0])