北大陈斌-Python语言基础与应用D5容器操作

tech2022-07-04  228

列表、元组基本操作 +,*,len(),[],in

>>> alist = [1,2,3,4,5] >>> blist = [4,5,6,7,8] >>> alist + blist [1, 2, 3, 4, 5, 4, 5, 6, 7, 8] >>> alist*3 [1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5] >>> len(alist) 5 >>> alist[1:5:2] [2, 4] >>> 3 in alist True >>> 6 in alist False

列表、元组高级操作 mylist = [1,2,3,4,5] 切片:获得[2,3,4],获得[3,4,5],获得[3,2,1],获得[1,3,5] mytpl = (1,2,3,4,5)同 t = ‘Mike and Tom’ split拆分、join合成为’Mike/and/Tom’ append列表末尾增长,insert列表中间增长,extend列表相接。 remove移走数据对象,clear清空列表,pop移走任意位置数据并返回移走数据,del删除指定位置数据。 reverse数据反向排,sort数据从小到大排,reversed,sort数据重新排原列表不受影响。 count计数,sum求和

>>> mylist = [1,2,3,4,5] >>> mylist[1:4:1] [2, 3, 4] >>> mylist[2::1] [3, 4, 5] >>> mylist[-3::-1] [3, 2, 1] >>> mylist[0::2] [1, 3, 5] >>> mytpl = (1,2,3,4,5) >>> mytpl[1:4:1] (2, 3, 4) >>> mytpl[2::1] (3, 4, 5) >>> mytpl[-3::-1] (3, 2, 1) >>> mytpl[0::2] (1, 3, 5) >>> t = 'Mike and Tom' >>> t.split(' ') ['Mike', 'and', 'Tom'] >>> '/'.join(['Mike','and','Tom']) 'Mike/and/Tom' >>> alist = [1,2,3,4,5] >>> blist = [4,5,6,7,8] >>> alist.append(6) >>> alist [1, 2, 3, 4, 5, 6] >>> alist.insert(1,7) >>> alist [1, 7, 2, 3, 4, 5] >>> alist.extend(blist) >>> alist [1, 7, 2, 3, 4, 4, 5, 6, 7, 8] >>> alist.remove(4) >>> alist [1, 7, 2, 3, 4, 5, 6, 7, 8] >>> alist.pop() 8 >>> alist [1, 7, 2, 3, 4, 5, 6, 7] >>> del alist[1] >>> alist [1, 2, 3, 4, 5, 6, 7] >>> alist.reverse() >>> alist [7, 6, 5, 4, 3, 2, 1] >>> alist.sort() >>> alist [1, 2, 3, 4, 5, 6, 7] >>> alist.count(1) 1 >>> sum(alist) 28

集合基本操作 a = set([1,2,3,4,5]) b = set([2,4,6,8,10]) c = set([1,2,3]) d = set([2,4,6]) 并、交、差、异或 添加、删除、判断子集、空集

>>> a = set([1,2,3,4,5]) >>> b = set([2,4,6,8,10]) >>> a|b {1, 2, 3, 4, 5, 6, 8, 10} >>> a&b {2, 4} >>> a-b {1, 3, 5} >>> b-a {8, 10, 6} >>> a^b {1, 3, 5, 6, 8, 10} >>> c = set([1,2,3]) >>> a.add(6) >>> a {1, 2, 3, 4, 5, 6} >>> a.add(1) >>> a {1, 2, 3, 4, 5, 6} >>> a.discard(6) >>> a {1, 2, 3, 4, 5} >>> a.pop() 1 >>> a {2, 3, 4, 5} >>> c.issubset(a) False >>> c.isempty() >>> c<=a False >>> d<=b True >>> a.isdisjoint(c) False

字典基本操作 mydict = {1:‘Mon’,‘line1’:3332} 添加、删除、是否空字典 取字典中所有key/value 判断key/value是否存在

>>> mydict = {1:'Mon','line1':3332} >>> mydict.update({2:'Tues'}) >>> mydict {1: 'Mon', 'line1': 3332, 2: 'Tues'} >>> 1 in mydict True >>> 1 in mydict.keys() True >>> 'Mon' in mydict.values() True
最新回复(0)