列表与数组类似,存储示意如下图:
1. 创建
#法1
lst=['hello','world',98]
#法2,list可以将()里的内容转换为列表
lst=list(['hello','world',98])
#法2并不多余,如:
lst=list(range(10))
lst=list('hello')
2.索引
#正向索引和逆向索引,下列代码均输出 hello
print(lst[0])
print(lst[-7])
3.获取指定元素的索引
lst=['hello','world',98,'hello']
print(lst.index('hello')) #返回0,因为有重复的返回第一个
print(lst.index('python')) #没有就报错
#从指定范围查找
print(lst.index('hello',1,4)) #从 1(world),2(98),3(hello)中查找
4.获取列表的单个元素
lst=['hello','wordl',98,'hello','world',234]
#正向
print(lst[2]) #98
#负向
print(lst[-3]) #hello
#超出范围
print(lst[10]) #报错
5.获取列表的多个元素
相当于获取一个字列表
lst=[10,20,30,40,50,60,70,80]
print('原列表',lst)
lst1=lst[1:6:1] #[start:stop:step]
print('切的片段',lst1) #20,30,40,50,60
#省略
print(lst[1:6:]) #step默认1
print(lst[:6:1]) #start默认0
print(lst[1::1]) #stop默认最后
#步长为负数
print(lst[::-1]) #80,70,60,50,40,30,20,10
print(lst[6:0:-1]) #70,60,50,40,30,20,
6.判断元素在列表中是否存在
#in or not in
lst=['hello',98,'world',32.3]
print('hello' in lst) #True
print(100 in lst) #False
print(100 not in lst) #True
7.列表元素的增加
末尾增加1个 lst.append(),末尾增加多个lst.extend(),
任意位置增加1 lst.insert(),任意位置增加多个 切片
lst=[10,20,30]
print('添加元素之前',lst,id(lst)) #[10,20,30] 13156131
lst.append(100)
print('添加元素之后',lst,id(lst)) #[10,20,30,100] 13156131
lst1=['hello','world']
#--------------------插入一个-------------------------------------
lst.append(lst1)
print(lst) #[10,20,30,100,['hello','world']],把lst当成一个元素
#--------------------插入多个-------------------------------------
lst.extend(lst1)
print(lst) #[10,20,30,100,'hello','world'],区分和append的区别
#--------------------任意位置插入1个------------------------------------
lst.insert(1,90)
print(lst) #[10,90,20,30,100]
#--------------------任意位置插入多个------------------------------------
lst2=[63,'hello']
lst[1:3:1]=lst2
print(lst) #[10,63,'hello',100]
#或者
lst[1::]=lst2
print(lst) #[10,63,'hello']
8.列表元素的删除
#remove 移除一个元素,重复元素只移第一个,没有报错
lst=[10,20,30,40,50,60,30]
lst.remove(30)
print(lst) #[10,20,40,50,60,30]
#pop 根据索引移除元素,pop如果不写参数,将删除最后一个元素
lst=[10,20,30,40,50,60,30]
lst.pop(1)
print(lst) #[10,30,40,50,60,30]
#切片删除至少一个元素,和切片插入一样,都是覆盖
lst=[10,20,30,40,50,60,30]
lst[1:3]=[]
print(lst) #[10,40,50,60,30]
#清除所有元素
lst=[10,20,30,40,50,60,30]
lst.clear()
print(lst) #[]
#清除列表对象
lst=[10,20,30,40,50,60,30]
del lst
print(lst) #报错
9.列表元素的修改
lst=[10,20,30,40]
#修改一个值
lst[2]=100 #[10,20,100,40]
#修改多个值
lst[1:3]=[300,400,500,600] #[10,300,400,500,600,40]
10.列表元素的排序
lst=[20,40,10,98,54]
#排序,sort(),默认升序,并未创建新的列表
lst.sort()
print('排序后',lst)
#进行降序排列
lst.sort(reverse=True) #()不写,默认reverse=False
print('排序后',lst)
#排序产生新列表,原列表不变
lst=[30,10,20,40]
new_lst=sorted(lst)
print(lst) #[30,10,20,40]
print(new_lst) #[10,20,30,40]
new_lst1=sorted(lst,reverse=True)
print(new_lst1) #[40,30,20,10]
11.列表生成式
lst=[i for i in range(1,10)]
print(lst) #[1,2,3,4,5,6,7,8,9]
lst=[i*i for i in range(1,10)]
print(lst) #[1,4,9,16,25,36,49,64,81]