笔记六
List列表
列表定义
list1 = [1,2,3,"KKK",[6,6,1]]
print(list1[0]) #1
print(list1[1]) #2
print(list1[2]) #3
print(list1[3]) #kkk
print(list1[4]) #[6,6,1]
print(list1[4][0]) #6
print(list1[4][1]) #6
print(list1[4][2]) #1
获取列表长度
print(len(list1)) #5
更新列表元素
list1[1] = 1
print(list1) #[1,1,3,"KKK",[6,6,1]]
列表加法&乘法操作
list1 = [1,2,3]
list2 = [4,5]
print(list1+list2) #[1,2,3,4,5]
print(list1*3) #[1,2,3,1,2,3,1,2,3]
列表的切片取值
list1 = [1,2,3,4,5,6]
print(list1[0:3]) #[1,2,3]
print(list1[-3:-1]) #[4,5]
print(list1[-3:]) #[4,5,6]
print(list1[:]) #[1,2,3,4,5,6]
print(list1[1:5]) #[2,3,4,5,]
print(list1[1:5:2]) #[2,4]
print(list1[::-1]) #[6,5,4,3,2,1]
del
del 关键字 删除
a = [1,2,3]
del a
print(a) #报错
b = [1,2,3]
del b[1]
print(b) #[1,3]
append()
append()向列表末尾添加元素
a = [1,2,3]
a.append(4)
print(a) #[1,2,3,4]
insert()
insert() 用于向列表中插入元素
参数1:插入的位置
参数2:插入的对象
list1 = [1,2,3,4]
list1.insert(0,5)
print(list1) #[5,1,2,3,4]
list2 = [1,2,3,4]
list2.insert(2,[5,6])
print(list2) #[1,2,[5,6],3,4]
clear()
list = [1,2,3,4]
list.clear()
print(list) #[]
print(len(list)) #0
remove()
remove() 用于从列表移除元素
若列表中有重复元素,只会移除第一个
a = ['hello','python','hello','world']
a.remove('hello')]
print(a) #['python','hello','world']
pop()
pop() 用于移除列表中指定位置的元素,并返回要移除的元素;在默认情况下,移除列表中最后一个元素
a = ['hello','python','hello','world']
a.pop(2)
print("要移除的数据:"a.pop(2)) #要移除的数据:hello
print(a) #['hello','python','world']
index()
index() 用于返回所匹配的元素的索引,只会匹配第一次
参数1:待查找的对象
参数2:查找的起始范围
参数3:查找的结束范围
a = ['hello','python','hello','world']
r1 = a.index('hello')
print(r1) #0
r2 = a.index('hello',1,3)
print(r2) #2
reverse()
reverse() 用于将列表反向排列
a = ['hello','python','hello','world']
a.reverse() #与 print(a[::-1]) 结果一致
print(a) #['world','hello','python','hello']
extend()
extend() :用于在列表的末尾添加另一个列表,与append函数相比,extend函数可以一次性添加多个元素
注意:使用extend函数和列表加法的结果是一样的,但是extend函数会将另一个列表并入当前列表,而列表加法是返回新的列表,为节约内存空间,更推荐使用extend函数来实现大列表的连接操作。
a = [1,2,3]
a.extend([4,5,6])
print(a) #[1,2,3,4,5,6]
copy()
copy(): 用于创建列表的副本
a = ['hello','python','hello','world']
b = a.copy()
del a[0]
print(b) #'hello','python','hello','world' 删除a中元素,对b没有影响
与下面示例进行区分
a = ['hello','python','hello','world']
b = a
del a[0]
print(b) #'python','hello','world' 删除a中元素,对b有影响
sort()
sort(): 用于将列表进行排序
ASCII码 大小规则:0~9<A~Z<a~z
a = ['hello','python','hw','world']
a.sort()
print(a) #['hello','hw','python','world']
b = ['hello','我','1']
b.sort()
print(b) #['1','hello',''我]
c = [1,2,3,'我']
c.sort()
print(c) #报错,只能对同类型的数据排序
d = [1,2,1,3,4]
d.sort()
print(d) #[1,1,2,3,4] 升序
d.sort(reverse=True)
print(d) #[4,3,2,1,1] 降序
count()
count(): 用于统计某个元素在列表中出现的次数
a = ['hello','python','hello','world']
b = a.count('hello')
print(b) #2