列表是什么?如何增删改查?如何排序?求表长?避免索引错误?
一、列表基本操作
关键记忆点:用[]表示列表,用逗号分割元素,列表名用复数的名称表示,打印会包含[]、访问列表元素(相当于数组名[])+增删改依次是查找titillates[i], 末尾添加dds.append(), 插入jjs.insert(0,"sd"), 删除del lls[0], 弹出 lls.pop(), lls.pop(1) , carname.remove('j')#删除某指定的第一个值
bicycles=['trek','sd','jih',"jo"]
print(bicycles)
print(bicycles[0].title())
bicycles=['trek','sd','jih',"jo"]
print(bicycles)
print(bicycles[-1])#[-1]是最后一个元素[-2]是倒数第二个
friends_names=["lai",'a','b','c','d']
print(f'{friends_names[0]},{friends_names[1]},{friends_names[-2]}')
friends_names=["lai",'a','b','c','d']
print(friends_names[1],friends_names[-2])
friends_names=["lai",'a','b','c','d']
count=0
while count<=4:
print(f'hello,{friends_names[count]}')
count+=1
carname=['j','v']
print(f'i would like to own a {carname[1]}')#查找
carname=['j','v']
carname[0]='kl'
print(carname)#修改
carname=['j','v']
carname.append('jjojojo')#增加
print(carname)
carname=['j','v']
carname.insert(1,'jjojojo')#插入'jjojojo'到carname[1]处
print(carname)
carname=['j','v']
carname.insert(1,'jjojojo')
del carname[0]#删除第一个元素
print(carname)
carname=['j','v']
carname.insert(1,'jjojojo')
jj=carname.pop()#弹出栈顶元素
kk=carname.pop(0)#弹出第一个元素
print(carname)
print(jj)
print(kk)
carname=['j','v']
carname.remove('j')#删除某值
print(carname)
二、管理列表
1、使用sort()对列表进行永久排序
carname.sort()#正序
carname.sort(reverse=True)#倒序
carname=['j','v','l']
carname.sort()#正序
print(carname)
carname.sort(reverse=True)#倒序
print(carname)
2、使用sorted()对列表进行临时排序
正序和倒序
print(sorted(carname))#正序
print(sorted(carname,reverse=True))#倒序
carname.reverse()#不能放入
carname=['j','v','l',"a"]
print(sorted(carname))#正序
print(carname)
carname=['j','v','l',"a"]
print(sorted(carname,reverse=True))#倒序
print(carname)
3、反转/向打印列表
carname=['a','b','c',"d"]
print(carname)
carname.reverse()#不能放入
print(carname)
carname.reverse()
print(carname)
4、确定列表的长度
carname=['a','b','c',"d"]
print(len(carname))
5、避免索引错误
列表索引差一特性
打印出来观察
carname=['a','b','c',"d"]
print(carname[4])