Python学习笔记(2)——对象类型
内置对象包括数字(123,1.2)、字符串(‘aaa’)、列表([])、字典({'a':'b','c':'d'})、元组(())、文件(fid=open(‘’,‘r’))、集合(set(‘abc’))、BOOL量等。
1、字符串
(1)字符串索引从0开始,正向索引从左边开始,反向索引从右边开始。
1 >>> s='spam' 2 >>> s[0]#正向索引 3 's' 4 >>> s[-1]#反向索引 5 'm'
(2)偏移量,x[i:j]为取出从偏移量为I(包括I)直到偏移量为J(不包括J)的内容
1 >>> s='spam' 2 >>> s[:]#全部字符 3 'spam' 4 >>> s[:2]#0开始到1 5 'sp' 6 >>> s[2:]#2开始到3 7 'am' 8 >>> s[:-1]#0开始到2(-1=3) 9 'spa'
(3)字符操作
1 >>> s='spam' 2 >>> s+'x'#plus 3 'spamx' 4 >>> s*2#repeat 5 'spamspam' 6 >>> s[1:]+'z'#new object 7 'pamz' 8 >>> 'z'+s[1:] 9 'zpam'
(4)类型特定方法
1 >>> s='spam' 2 >>> s.find('pa')#return the lowest index where the substring is found 3 1 4 >>> s.isalpha()#contents:isalpha,isdigit,etc 5 True 6 >>> s.upper()#capital 7 'SPAM' 8 >>> s.lower()#lowercase 9 'spam' 10 >>> s=' spam ' 11 >>> s.strip()#remove the former and the last space 12 'spam'
2、列表
(1)类型特定操作
1 >>> l=[2,1,3] 2 >>> l.append('c')#add 3 >>> l 4 [2, 1, 3, 'c'] 5 >>> l.pop(3)#remove 6 'c' 7 >>> l 8 [2, 1, 3] 9 >>> l.sort()#sort 10 >>> l 11 [1, 2, 3] 12 >>> l.reverse()#reverse 13 >>> l 14 [3, 2, 1]
(2)嵌套
1 >>> m=[[1,2,3],[4,5,6],[7,8,9]]#二维数组 2 >>> m 3 [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 4 >>> m[1]#单维访问 5 [4, 5, 6] 6 >>> m[1][2]#二维访问 7 6
(3)列表解析表达式
1 >>> m=[[1,2,3],[4,5,6],[7,8,9]] 2 >>> [row[1] for row in m]#矩阵每一行中的第2个元素 3 >>> [2, 5, 8] 4 >>> [row[1]+1 for row in m]#矩阵每一行中的第2个元素加1 5 [3, 6, 9] 6 >>> [row[1] for row in m if row[1]%2==0]#矩阵每一行中的第2个元素,且元素能够整除2 7 [2, 8] 8 >>> [m[i][i] for i in [0,1,2]]#矩阵对角线元素 9 [1, 5, 9] 10 >>> [c*2 for c in 'spam']#repeat characters 11 ['ss', 'pp', 'aa', 'mm'] 12 >>> G=(sum(row) for row in m)#括号内解析语法 13 >>> next(G)#迭代器 14 6 15 >>> next(G) 16 15 17 >>> next(G) 18 24 19 >>> next(G)#迭代溢出 20 Traceback (most recent call last): 21 File "<pyshell#98>", line 1, in <module> 22 next(G) 23 StopIteration
3、元组
元组的意义在于其不可变性,提供一种完整的约束。
>>> s=(1,2,3) >>> s+(4,5) (1, 2, 3, 4, 5) >>> s.index(3)#3的位置 2 >>> s.count(3)#3出现的次数 1
4、最后
以上函数都可通过dir(s)来查找,dir简单给出了操作的名称,通过help来查询函数的作用。
1 'SPAM' 2 >>> dir(s) 3 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] 4 >>> help(s.__add__) 5 Help on method-wrapper object: