最近,由于工作需要,使用python开发公司的运维自动化平台,所以找本书来并结合官方手册,开始python的学习之旅。
一、列表
【含义】:列表用中括号表示,通过逗号进行分隔一组数据(可以为不同的数据类型),如以下的声明:
1>>> language = ['chinese','english','japanese']2>>> contries = ['China','Amercia','England','Japan']34>>> edward = ['Edward Gumby',42]#不同的数据类型5>>> john = ['John Smith',50]6>>> database = [edward,john]#列表可以嵌套
【操作】:访问、插入、删除、求最大值最小值及长度等
1、访问:可以通过索引或分片进行列表的遍历访问,索引可以访问某个位置的值,分片可以灵活的访问一定范围的值,如下所示:
1>>> language = ['chinese','english','japanese']2#索引访问3>>>language[0]4'chinese'56#分片访问7#第一个索引元素包括在分片中,第二个索引不包括在分片中8#可以设置分片的步长9>>>language[::]10['chinese','english','japanese']11>>> language[0:3]12['chinese','english','japanese']13>>> language[0:2]14['chinese','english']15>>> language[1:2]16['english']17#设置步长为218>>> num = [1,2,3,4,5,6,7,8,9]19>>> num[0:9:2]20[1, 3, 5, 7, 9]
21 >>> num = [1, 2, 3]
22 >>> max(num)
23 3
24 >>> min(num)
25 1
26 >>> len(num)
27 3
2、修改、插入和删除操作,由此看来列表是可以进行修改的。
1#修改列表某个元素:索引赋值2>>> num = [1,2,3]3>>> num[0]=5#必须为存在的位置索引赋值,否则报错4>>>num5[5, 2, 3]67#修改列表某段范围的值:分片赋值8>>> num[2:]=[6,7,9]#分片赋值元素个数可以不等长9>>>num10[5, 2, 6, 7, 9]1112#删除某个元素13>>>delnum[4]14>>>num15[5, 2, 6, 7]
【方法】对于列表,python内置了诸多方法供操作,主要常用的有以下几个:
1#append方法:用于在列表最后添加元素,该方法直接修改原列表并返回修改完后的新列表2>>> str = ['a','b','c','d']3>>> str.append('e')4>>>str5['a','b','c','d','e']67#count方法:统计某个元素在列表中出现的次数8>>> str = ['a','b','c','d']9>>> str.count('a')1011112#extend方法:list.extend(L),L指的是列表对象13#用另一个列表扩展一个列表,相当于两个列表连接,14#但是又不同于连接操作,因为extend方法直接修改原列表并返回,15#连接操作不影响原有的列表值16>>> str1 = ['hello,']17>>> str2 = ['world']18>>>str1.extend(str2)19>>>str120['hello,','world']2122>>> str3 = ['a']23>>> str4 = ['5']24>>> str3 = str3+str4#效率没有extend高25>>>str326['a','5']2728#index方法:返回匹配项的第一个索引位置29>>> knight = ['we','you','we','me','he']30>>> knight.index('we')3103233#insert方法:list.insert(i, x)插入x到该i位置34>>> knight.insert(1,'she')35>>>knight36['we','she','you','we','me','he']3738#remove方法:list.remove(x)39#删除列表中为X的第一个出现元素40>>> knight = ['we','she','you','we','me','he']41>>> knight.remove('we')42>>>knight43['she','you','we','me','he']4445#reverse方法:将元素倒序存储46>>> str = ['a','b']47>>>str.reverse()48>>>str49['b','a']5051#sort方法:list.sort(key=None, reverse=False)52#直接改变原列表顺序,而不是改变副本,对于这种需求如53#仅仅对副本进行排序,不改变原列表不能直接用sort54>>> num = [1,3,2,4]55>>>num.sort()56>>>num57[1, 2, 3, 4]5859#pop方法:list.pop([i])60#删除指定索引位置的元素值,并返回该值61>>> num = [1, 2, 3, 4]62>>> num.pop(3)634
【常用举例】:模拟实现堆栈操作和队列操作
堆栈:后进先出
1>>> stack = [3, 4, 5]2>>> stack.append(6)3>>> stack.append(7)4>>>stack5[3, 4, 5, 6, 7]6>>>stack.pop()778>>>stack9[3, 4, 5, 6]10>>>stack.pop()11612>>>stack.pop()13514>>>stack15[3, 4]
队列:先进先出
1>>>fromcollectionsimportdeque2>>> queue = deque(["Eric","John","Michael"])3>>> queue.append("Terry")#Terry arrives4>>> queue.append("Graham")#Graham arrives5>>> queue.popleft()#The first to arrive now leaves6'Eric'7>>> queue.popleft()#The second to arrive now leaves8'John'9>>> queue#Remaining queue in order of arrival10deque(['Michael','Terry','Graham'])