列表的创建
创建列表的方式
1.使用中括号
2.调用内置函list()
lst=['hello','world',666] #使用中括号创建列表
lst2=list(['hello','world',666])#使用list内置函数创建列表
列表的查询操作
1.获取列表中指定元素的索引
lst=['hello','world',666,'hello']
print(lst.index('hello'))
'''从上面的列表中寻找hello的索引
如果列表中又相同元素只返回列表中
相同元素的第一个元素的索引
'''
print(lst.index('hello',1,4))#从1-4的索引中寻找hello的索引
2.获取列表中的单个元素
lst=['hello','world',666,'hello']
print(lst[0])
print(lst[-1])
print(lst[-2])
'''
输出内容
hello
hello
666
'''
3.获取列表中的多个元素
lst=[1,2,3,4,5,6,7,8]
print(lst[1:6:1])#从第2位开始到第5位结束,步长为1
#[2, 3, 4, 5, 6]
print(lst[0:8:2])#从1位开始到第7位结束,步长为2
#[1, 3, 5, 7]
4.判断指定元素在列表中是否存在
lst=[1,2,3,'k','hello','python']
print('b' in lst)#False
print('k' in lst)#True
5.遍历输出数组
lst=[1,2,3,'k','hello','python']
for i in lst:
print(i)
列表元素中的增删改操作
1.列表元素的增加操作
lst=[10,20,30,40]
lst.append(50)#末尾增加一个元素
print(lst)
#[10, 20, 30, 40, 50]
lst2=[999,000]
lst.extend(lst2)#向末尾一次增加多个元素
print(lst)
#[10, 20, 30, 40, 50, 999, 0]
#在任意位置插入元素
lst.insert(2,88)#在索引为2的位置插入88
print(lst)
#[10, 20, 88, 30, 40, 50, 999, 0]
#在任意的位置上添加多个元素
lst3=['你好','8888']
lst[2:]=lst3 从索引为2的位置切掉后面的元素,将lst3的元素赋值到lst
print(lst)
#[10, 20, '你好', '8888']
列表元素的删除操作
- remove()
从列表中移除一个元素,如果有重复元素只移第一个元素
lst=[10,20,30,40,50,60,70,10]
lst.remove(10)#从列表中移除一个元素,如果有重复元素只移第一个元素
print(lst)
#[20, 30, 40, 50, 60, 70, 10]
- pop()
根据索引移除元素
lst=[10,20,30,40,50,60,70,10]
lst.pop(7)
print(lst)
#[10, 20, 30, 40, 50, 60, 70]
lst.pop()#如果不指定索引,将移除最后一个
print(lst)
#[10, 20, 30, 40, 50, 60]
- 切片操作
删除至少一个元素,将产生一个新的列表对象
lst=[10,20,30,40,50,60,70,80,90,]
lst2=lst[2:5]#从第二位开始到第5位
print(lst2)
#[30, 40, 50]
- clear()
清除列表中的所有元素
lst=[10,20,30,40,50,60,70,80,90,]
lst.clear()
print(lst)
#[]
5.del
将列表元素删除
lst=[10,20,30,40,50,60,70,80,90,]
del lst
列表元素的修改操作
lst=[10,20,30,40,50,60,70,80,90]
lst[3]=100 #一次修改一个值
print(lst)
#[10, 20, 30, 100, 50, 60, 70, 80, 90]
lst[1:3]=[1000,2000,3000,4000]
print(lst) #一次修改多个值
#[10, 1000, 2000, 3000, 4000, 100, 50, 60, 70, 80, 90]
列表元素的排序操作
sort()和sorted()函数
lst=[1,3,5,7,9,2,4,6,8,10]
lst.sort() #默认升序
print(lst)
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst.sort(reverse=True) #降序
print(lst)
#[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
'''
也可以使用第二种方法,
使用内置函数sorted()对列表进行排序,
将产生一个新的列表对象
'''
lst=[1,3,5,7,9,2,4,6,8,10]
lst2=sorted(lst)
print(lst)#[1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
print(lst2)#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 新的列表
#降序排序
lst3=sorted(lst,reverse=True)
print(lst3) #[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
列表生成式
lst=[i for i in range(1,11)]
print(lst) #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
lst2=[j*2 for j in range(1,11)]
print(lst2) #[2, 4, 6, 8, 10, 12, 14, 16, 1