一、list(列表)
list是Python里的一种容器,里面可以存储多个任何类型的数据,长度也可以任意伸缩,可以像C语言中数组那样,按照索引下标获取对应的值。但数组是一个存储多个固定类型变量的连续内存块空间,list则可以存储任意类型数据(怀疑里面存的是泛型指针(void)* ,由解释器自行判断变量类型并改变指针类型?)
>>> li = ['alex',[1,2,3],'wusir','egon','女神','taibai'] >>> print(li) ['alex', [1, 2, 3], 'wusir', 'egon', '女神', 'taibai'] >>> l1 = li[0] >>> l1 'alex' >>> l2 = li[1] >>> l2 [1, 2, 3] >>> l3 = li[0:3] >>> l3 ['alex', [1, 2, 3], 'wusir']
list的常用操作有增、删、查、改,类似关系型数据库。下面详细介绍:
1. 增加元素(3种常用操作)
1.1 append(value)
在list末尾追加1个元素
>>> students = [] # 将students赋值为一个空列表 >>> students.append(123) >>> students[-1] 123 >>> students.append("日天") >>> students [123, '日天']
例子:用input()给一个学生名字列表中不断添加新学生,用户输入为小写或大写字母’q’则停止添加
students = []; while 1: username = input(">>>"); if username.strip().upper() == 'Q': break; else: students.append(username); print(students);
运行结果如下:
>>>wy >>>czy >>>xjj >>>q ['wy', 'czy', 'xjj']
1.2 insert(index, value)
在list索引为index的位置插入1个元素,原索引位置及后面的元素自动向后顺延
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> students.insert(2, 123) # 将数字123插入到students[2]的位置 >>> students ['wy', 'czy', 123, 'xjj', 'xzf'] # 123位于students[2], "xjj"和"xzf"依次顺延为索引3和4的位置
1.3 extend(iterable_obj)
将一个可迭代的对象拆分后,依次追加在列表末尾。可迭代对象包括str, list, tuple, dict等多种数据类型。如果参数不是可迭代对象,直接报错
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> students.extend("123") # 将str类型数据追加至list末尾 >>> students ['wy', 'czy', 'xjj', 'xzf', '1', '2', '3'] >>> students = students[-3:] >>> students ['1', '2', '3'] >>> students.extend(["Linux", "FreeBSD", "Unix", 3.1415926]) # 将list类型数据追加至list末尾 >>> students ['1', '2', '3', 'Linux', 'FreeBSD', 'Unix', 3.1415926] >>> students.extend((1, 3)) # 将tuple类型数据追加至list末尾 >>> students ['1', '2', '3', 'Linux', 'FreeBSD', 'Unix', 3.1415926, 1, 3] >>> students = students[:-2] >>> students ['1', '2', '3', 'Linux', 'FreeBSD', 'Unix', 3.1415926] # 试试将456这个int类型数据(不可迭代对象)用extend方法追加至list末尾,结果就会报错,显示 TypeError: 'int' object is not iterable (int不是可迭代对象),此时应该使用append方法追加 >>> students.extend(456) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-2b24a1ec749d> in <module> 1 students = []; ----> 2 students.extend(456); TypeError: 'int' object is not iterable >>>
2. 删除元素(4种常用操作)
2.1 remove(value)
删除list中值为value的元素。如果value不存在于list中,直接报错。因此可以先判断x in list, 确保万无一失
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> students.remove("czy") >>> students ['wy', 'xjj', 'xzf'] >>> students.remove(123) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-7-02c036a833fe> in <module> 1 students = []; ----> 2 students.remove(123) ValueError: list.remove(x): x not in list
2.2 del list(index)
删除list[index]的元素。如果索引值不合理,直接报错
>>> protocol = ["ospf", "isis", "bgp", "rip", "ip", "ipv6", "tcp", "udp"] >>> del protocol[0] >>> protocol ['isis', 'bgp', 'rip', 'ip', 'ipv6', 'tcp', 'udp'] >>> del protocol[-2] >>> protocol ['isis', 'bgp', 'rip', 'ip', 'ipv6', 'udp'] >>> del protocol[:-1] # del支持切片删除,删除除最后一个元素以外的所有元素 >>> protocol ['udp'] >>> del protocol[1] # 删除不存在的索引值直接报错 --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-4-f4e1bb9c187f> in <module> 1 protocol = ["udp"] ----> 2 del protocol[1] IndexError: list assignment index out of range
2.3 pop(index)
删除list[index]元素并返回被删除的元素值(类似于del,但del并不会返回元素值),index为空默认删除最后一个元素,index不合理直接报错。
pop和append结合使用,可以让list可以模仿stack数据结构
>>> students = ['wy', 'czy', 'xjj', 'xzf'] # 删除students[0] >>> students.pop(0) 'wy' # 删除了"wy"并返回了这个值 >>> students ['czy', 'xjj', 'xzf'] >>> students.pop(1) 'xjj' >>> students.pop() # 参数为空默认删除最后一个元素 'xzf' >>> students ['czy'] >>> students.pop(1) # 删除不存在的索引值报错 ---------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-3-a236b1b1cc3a> in <module> 1 students = ["czy"] ----> 2 students.pop(1) IndexError: pop index out of range
2.4 clear()
清空列表,没有参数
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> students.clear() >>> students [] >>>
3. 查询元素(3种常用操作)
索引取值、索引切片取值、循环遍历
>>> protocol = ["ospf", "isis", "bgp", "rip", "ip", "ipv6", "tcp", "udp"] >>> protocol[3] 'rip' >>> protocol[2:6] ['bgp', 'rip', 'ip', 'ipv6'] # 循环遍历 for p in protocols: print(p, end = " ") # 循环遍历结果 ospf isis bgp rip ip ipv6 tcp udp
4. 修改元素(2种常用操作)
4.1 索引访问修改
1 >>> students = ['wy', 'czy', 'xjj', 'xzf'] 2 >>> students[2] = "WuShu" 3 >>> students 4 ['wy', 'czy', 'WuShu', 'xzf']
4.2 索引切片修改(必须是个可迭代对象iterable_obj)
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> students[0:2] = "云姐plfd" >>> students ['云', '姐', 'p', 'l', 'f', 'd', 'xjj', 'xzf'] >>> students[0:2] = "XY" # ”XY“为可迭代对象,如list, tuple, str等 >>> students ['X', 'Y', 'p', 'l', 'f', 'd', 'xjj', 'xzf'] >>> students[0:3] = "XY" >>> students ['X', 'Y', 'l', 'f', 'd', 'xjj', 'xzf'] >>>
5. 公共方法(len, count, index, sort, reverse)
5.1 len(list),len为函数
显示列表元素的个数
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> len(students) 4 >>>
5.2 count(value),count为list对象方法
计算list中value出现的次数,value为空报错
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> students.count("wy") # 显示students中"wy"出现的次数 1 >>> students.count(1) 0 >>> students.count() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-10-7358caf689b5> in <module> 1 students = [] ----> 2students.count() TypeError: count() takes exactly one argument (0 given)
5.3 index(value),index为list对象方法
计算list中value值第一次出现的索引位置,value为空或者不存在都将报错
>>> students = ['wy', 'czy', 'xjj', 'xzf'] >>> students.index("xjj") 2 >>> students.index(123) # students中没有123,直接报错 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-14-42a3ab695f28> in <module> 1 students = ['wy', 'czy', 'xjj', 'xzf'] 2 print(students.index("xjj")) ----> 3print(students.index(123)) ValueError: 123 is not in list >>> students.index() # index参数为空,直接报错 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-15-c99f5e25284d> in <module> 1 students = ['wy', 'czy', 'xjj', 'xzf'] 2 print(students.index("xjj")) ----> 3print(students.index()) TypeError: index() takes at least 1 argument (0 given)
5.4 sort(),sort为list对象方法
对list元素排序,默认为从小到大,加入参数reverse=True为反向排序
>>> num = [1, 4, 3, 7, 5] >>> num.sort() >>> num [1, 3, 4, 5, 7] >>> num.sort(reverse = 1) # reverse参数也可以写成True(True转为数字即为1) >>> num [7, 5, 4, 3, 1] >>>
5.6 reverse(),reverse为list对象方法
对list元素反转
>>> num = [1, 4, 3, 7, 5] >>> num.reverse() >>> num [5, 7, 3, 4, 1]
6. list嵌套
列表中的元素可以是列表等可迭代对象,访问方式类似C语言中的多维数组(数组的数组)
>>> name = ['taibai','武藤兰','苑昊',['alex','egon',89],23] >>> name[3][2] 89 >>> name[3][2] = "FreeBSD" >>> name ['taibai', '武藤兰', '苑昊', ['alex', 'egon', 'FreeBSD'], 23] >>> name[3][1][-1] 'n' >>> name[3][1] = 500 >>> name ['taibai', '武藤兰', '苑昊', ['alex', 500, 'FreeBSD'], 23] >>> name[3][0].upper() 'ALEX'
二、tuple(列表)
tuple和list类似,也是是Python里的一种容器,里面可以存储多个任何类型的数据。但tuple里的元素在初始化以后固定,不可以做任何的修改,否则报错