当前位置: 首页 > 后端技术 > Python

Python:列表list

时间:2023-03-25 21:32:31 Python

List列表可以存储多种不同类型的数据,存储每个数据对象的引用,类似于其他语言的数组概念创建列表,使用[]lst=['1','2']两种方式内置函数list()lst2=list(['1','2'])列表的特点列表数据按顺序排列,索引映射唯一一个数据。索引从左到右,从0开始,索引从右到左。它可以存储从-1开始的重复数据。可以混合任何类型的数据。根据需要动态分配和回收内存。index():获取列表中某个列表元素的索引list1=['hello1','hello2','hello3','hello']print(list1.index('hello'))#只返回索引ofthefirstelementfound#print(list1.index('hell'))#如果元素不存在,抛出ValueErrorprint(list1.index('hello',1,4))#可以指定搜索范围,不包括end根据index获取list中的一个元素print(list1[-2])#Output'hello3'print(list1[3])#Output'hello'#print(list1[-7])#indexout的范围,并抛出异常IndexError获取列表中的多个元素:slice操作语法:列表名[start:stop:step]start:默认为0stop:no包括停止索引元素,不写到结束步骤:默认为1list2=[1,2,3,4,5,6,7,8,9,10]#复制原列表生成新列表与原列表引用id不同print(list2[1:5:1])#输出[2,3,4,5]print(list2[:2])#输出[1,2]print(list2[::])#输出[1,2,3,4,5,6,7,8,9,10]print(list2[1::])#输出[2,3,4,5,6,7,8,9,10]#步长为负数,切片逆序输出print(list2[::-1])#output[10,9,8,7,6,5,4,3,2,1]print(list2[10::-1])#输出[10,9,8,7,6,5,4,3,2,1]print(list2[5::-1])#输出[6,5,4,3,2,1]print(list2[::-2])#输出[10,8,6,4,2]判断一个元素是否存在于列表中,in/notinprint(1inlist2)#Trueprint(1notinlist2)#false遍历列表的元素foriteminlist2:print(item,end='\t')#输出[1,2,3,4,5,6,7,8,9,10]列表元素的增删改查添加操作1.append():追加一个元素到列表的末尾listlist2.append(11)print(list2)#Output[1,2,3,4,5,6,7,8,9,10,11]2.extend():在末尾追加一个或多个元素list2.extend(list1)print(list2)#output[1,2,3,4,5,6,7,8,9,10,11,'hello1','hello2','hello3','你好']3。insert():在任意位置插入一个元素,后面元素的顺序会后移list2.insert(1,122)print(list2)#Output[1,122,2,3,4,5,6、7、8、9、10、11、'你好1'、'你好2'、'你好3'、'你好']4。切片操作:在任意位置添加多个元素,先切片再替换切掉的部分list2[:5:]=list1print(list2)#Output:['hello1','hello2','hello3','hello',5,6,7,8,9,10,11,'hello1','hello2','hello3','hello']删除操作1.remove():删除指定元素list2.remove('hello')#只删除第一个,不存在会报错ValueErrorprint(list2)#Output['hello1','hello2','hello3',5,6,7,8,9,10,11,'你好1','hello2','hello3','hello']2.pop():根据索引删除元素,如果没有写入索引,默认删除最后一个元素,如果指定索引不存在,则抛出异常会抛出IndexErrorlist2.pop(1)print(list2)#Output['hello1','hello3',5,6,7,8,9,10,11,'hello1','hello2','hello3','hello']3.切片操作:每次至少删除一个元素,生成新的列表对象newList=list2[1:3]print(newList)#output['hello3',5]#不生成新的对象,操作原数组list2[1:3]=[]print(list2)#输出['hello1',6,7,8,9,10,11,'hello1','hello2','hello3','hello']4.clear():清除列表list2.clear()print(list2)#Output[]5.del:deletelistdellist2#print(list2)#NameError:name'list2'isnotdefined修改操作1.修改指定索引的元素list2=[1,2,3,4,5]list2[2]=100print(list2)#output[1,2,100,4,5]2.切片替换list2[1:2]=[10,20,30]print(list2)#输出[1,10,20,30,100,4,5]排序操作1.sort():默认排序从从小到大,指定reverse=True,降序,操作的是原列表list3=[11,15,2,8,5,4,6,3]list3.sort()print(list3)#[2,3,4,5,6,8,11,15]list3.sort(reverse=True)print(list3)#[15,11,8,6,5,4,3,2]2.sorted():内置-在函数中;默认从小到大排序,指定reverse=True,降序排列;原列表不变,生成新列表list4=[11,15,2,8,5,4,6,3]nl=sorted(list4)print(nl)#[2,3,4,5,6,8,11,15]nl=sorted(list4,reverse=True)print(nl)#[15,11,8,6,5,4,3,2]列表生成(列表元素有规则)语法:[i*iforiinrange(1,10)]i*i:列表元素的表达式,通常包括自定义变量i:自定义变量范围(1,10):可迭代对象list5=[i*iforiinrange(1,10)]print(list5)#[1,4,9,16,25,36,49,64,81]list6=[i*2foriinrange(1,6)]print(list6)#[2,4,6,8,10]