List补充,系列四讲中介绍列表面向的是有一定python基础的同学,下面我来做一个列表的补充作为补充。
列表可以说是python最常用的数据类型,地位自然不用说了。
1.创建列表,下面给出三种方法:
#方法1List = [1, 2, 4, 8, 16, 32,64]#方法2List = []for x in range(0, 7): List.append(2**x)#方法3List= [2**x for x in range(0, 7)]
2.增加元素
A.在列表末尾添加元素
list = [1, 2, 3]list.append(4) #得到 [1, 2, 3, 4]
B.在列表插入元素
1ist = [1, 2, 3]1ist.insert(1,9) #[1, 9, 2, 3]
C.列表相加
#第一种表示形式list1= [1, 2, 3]list2 = list1 + [4, 5, 6] #第二种表示形式list1.extend([4, 5, 6]) #直接扩增list
3.删除元素
A.del语句
list = [1, 2, 3, 4, 5, 6]del list[0] #得到[2, 3, 4, 5, 6]del list[0:3] #得到[5, 6]
B.pop()删除方法
list = [1, 2, 3, 4, 5]m = list.pop(1) #m=2n = list.pop(2) #n=3
C.remove函数方法
list = [1,2,3,1,2]list.remove(2)print(list)#得到[1, 3, 1, 2]
ps:在del语句和pop()有一个判断标准,如果列表删除一个元素,且不再使用del语句,如果删除后还要继续用用pop()。
pop()使用方法补充:
list = [1,2,3,1,2]print(list)#[1, 2, 3, 1, 2]l_list=list.pop()print(list)#[1, 2, 3, 1]print(l_list)#2
4.组织列表
A.sort()对列表永久排序
list= [5,3,2,1,4]list.sort()print(list)#得到[1,2,3,4,5] 默认输出升序list=['d','b','a','c']list.sort()print(list)#输出['a', 'b', 'c', 'd'] 默认输出正序
B.sorted函数
list=['d','b','a','c']print(list)#['d', 'b', 'a', 'c']print(sorted(list))#['a', 'b', 'c', 'd']print(list)#['d', 'b', 'a', 'c']
可以看出来sorted函数是临时排序
C.倒着打印输出reverse()函数
list=['d','b','a','c']print(list)#['d', 'b', 'a', 'c']list.reverse()print(list)#['c', 'a', 'b', 'd']
附一张思维导图
![f27b7d4c031b6d63532e658e7683f840.png](https://img-blog.csdnimg.cn/img_convert/f27b7d4c031b6d63532e658e7683f840.png)