python基本对象类型
文章目錄
- python對象類型
- 1.數(shù)字
- 2.字符串
- 3.列表
- 4.字典
- 5.元組
- 6.文件
- 7.其他核心類型
python對象類型
1.數(shù)字
例子
>>> 123+222 345 >>> 1.5*399 598.5 >>> 2**10 1024 >>> 3.1415*2 6.283 >>> 9.9999+1 10.9999 >>> import math >>> math.pi 3.141592653589793 >>> math.sqrt(80) 8.94427190999916 >>> import random >>> random.random() 0.3359936409813997 >>> random.choice([1,2,3,4]) 1 >>> random.choice([5,2,3,4]) 4可以看出:
1.python支持一般的數(shù)學運算
2.還可以導入一些數(shù)學模塊,比如math,random模塊。
2.字符串
>>> S='span' >>> len(S) 4 >>> S[0] 's' >>> S[1] 'p' >>> S[-1] 'n' >>> S[-2] 'a' >>> S[len(S)-1] 'n' >>> S[1:3] 'pa' >>> S[1:] 'pan' >>> S[:-1] 'spa' >>> S[:0] '' >>> S[0:] 'span' >>> S[:] 'span' >>> S 'span' >>> S+'xyz' 'spanxyz' >>> S*8 'spanspanspanspanspanspanspanspan' >>> S[0]='z' Traceback (most recent call last):File "<pyshell#28>", line 1, in <module>S[0]='z' TypeError: 'str' object does not support item assignment >>> S='z'+S[1:] >>> S 'zpan' >>> S.find('pa') 1 >>> S.replace('pa','xyz') 'zxyzn' >>> S 'zpan' >>> line='aaa,bbb,ccc,ddd' >>> line.split(',') ['aaa', 'bbb', 'ccc', 'ddd'] >>> S='jymmm' >>> S.upper() 'JYMMM' >>> S.isalpha() True >>> line 'aaa,bbb,ccc,ddd' >>> line=line+'\n' >>> line 'aaa,bbb,ccc,ddd\n' >>> line='aaa,bbb,ccc,ddd\n' >>> line 'aaa,bbb,ccc,ddd\n' >>> line=line.rstrip() >>> line 'aaa,bbb,ccc,ddd' >>> '%s,eggs,and%s'%('span','sjdi!') 'span,eggs,andsjdi!' >>> '{0},eggs,and {1}'.format('spann','isjdi') 'spann,eggs,and isjdi' >>> S='A\nB\tC' >>> len(S) 5 >>> ord('S') 83 >>> import re >>> match = re.match('Hello[ \t]*(.*)world','Hello Python world') >>> match.group(1) 'Python ' >>> match=re.match('/(.*)/(.*)/(.*)','/usr/home/jdsis') >>> match.groups() ('usr', 'home', 'jdsis') >>> dir(S) ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__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'] >>> help(S.replace) Help on built-in function replace:replace(...) method of builtins.str instanceS.replace(old, new[, count]) -> strReturn a copy of S with all occurrences of substringold replaced by new. If the optional argument count isgiven, only the first count occurrences are replaced.可以看出:
1.對于字符串來說,他本身就是一個序列,所謂序列就類似于數(shù)組,一個包含其他對象的有序集合。因此他是有位置順序的。那么我們就可以像數(shù)組一樣對字符串進行操作。
2.對于索引來說,我們可以正向索引,也可以反向索引,正向的話就是和數(shù)組一樣,下標從零開始,零對應的是第一個元素。而反向的話,則是從-1開始,-1對應了最后一個元素。
3.序列也支持分片操作,S[1:3]意思就是取出字符串的[1,3)下標,也就是下標1和下標2。如果[:]兩邊有一個是沒寫數(shù),那么說明是從頭開始或者是到結尾結束。
4.序列也支持用數(shù)學符號進行合并
5.從例子中我們發(fā)現(xiàn),字符串具有不可變形,就是說你無論怎么對原始字符串進行操作,最終原始字符串都不會發(fā)生改變。所以為了改變原始字符串,我們通常需要建立一個新的字符串,并以同一變量名對其賦值。
6.字符串也具有一些操作方法,比如find,replace,upper,isalpha等等
7.我們也可以對字符串對象進行模式匹配
8.尋求幫助:dir和help,dir返回一個列表,其中包含了對象的所有屬性,包括方法名稱,然后我們用help查詢方法就可以知道他是做什么怎么用的
3.列表
>>> L=[123,'spsdis',1.232] >>> len(L) 3 >>> L[0] 123 >>> L[:-1] [123, 'spsdis'] >>> L+[4,5,6] [123, 'spsdis', 1.232, 4, 5, 6] >>> L [123, 'spsdis', 1.232] >>> L.append('NNI') >>> L [123, 'spsdis', 1.232, 'NNI'] >>> L.pop(2) 1.232 >>> L [123, 'spsdis', 'NNI'] >>> M=['ss','sssd','sff'] >>> M.sort() >>> M ['sff', 'ss', 'sssd'] >>> M.reverse() >>> M ['sssd', 'ss', 'sff'] >>> L[99] Traceback (most recent call last):File "<pyshell#74>", line 1, in <module>L[99] IndexError: list index out of range >>> L[99]=1 Traceback (most recent call last):File "<pyshell#75>", line 1, in <module>L[99]=1 IndexError: list assignment index out of range >>> M=[[1,2,3],[4,5,6],[7,8,9]] >>> M [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> M[1] [4, 5, 6] >>> M[1][2] 6 >>> col2=[row[1] for row in M] >>> col2 [2, 5, 8] >>> M [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> [row[1]+1 for row in M] [3, 6, 9] >>> [row[1] for row in M if row[1]%2==0] [2, 8] >>> diag=[M[i][i]for i in [0,1,2]] >>> diag [1, 5, 9] >>> S 'A\nB\tC' >>> doubles=[c*2 for c in 'djfijsi'] >>> doubles ['dd', 'jj', 'ff', 'ii', 'jj', 'ss', 'ii'] >>> G=(sum(row) for row in M) >>> next(G) 6 >>> next(G) 15 >>> list(map(sum,M)) [6, 15, 24] >>> {sum(row) for row in M} {24, 6, 15} >>> {i:sum(M[i]) for i in range(3)} {0: 6, 1: 15, 2: 24} >>> [ord(x) for x in 'sdffs'] [115, 100, 102, 102, 115] >>> {ord(x) for x in 'sdffs'} {115, 100, 102} >>> {x:ord(x) for x in 'sdffs'} {'s': 115, 'd': 100, 'f': 102}可以看出:
1.列表是一個任意類型的對象的位置相關的有序集合,其大小可變
2.能夠對列表進行索引,切片,合并等操作,但是這樣不會對原列表修改
3.還具有其列表類型特定的操作,append,pop,這里是可以直接對列表進行增加或縮減。還有sort,按從小到大順序對列表進行排序,reverse,翻轉字符串
4.盡管列表沒有固定大小,但是python不能引用不存在的元素,對列表末尾范圍之外進行索引或賦值會報錯
5.支持任意類型的嵌套,一個嵌套列表的列表能實現(xiàn)二維矩陣
6.列表解析:通過對序列中的每一項運行一個表達式來創(chuàng)建一個新列表。可以加上if語句進行判斷,或是再前面變量進行不同的操作。列表,集合和字典都可用解析來創(chuàng)建
4.字典
>>> D={'food':'nuddle','quantity':4,'color':'pink'} >>> D['food'] 'nuddle' >>> D['quantity']+=1 >>> D {'food': 'nuddle', 'quantity': 5, 'color': 'pink'} >>> D={} >>> D['name']='BOb' >>> D['job']='dev' >>> D['age']=40 >>> D {'name': 'BOb', 'job': 'dev', 'age': 40} >>> print(D['name']) BOb >>> rec={'name':{'first':'bob','last':'smith'},'job':['dev','mgr'],'age':40.5} >>> rec['name'] {'first': 'bob', 'last': 'smith'} >>> rec['name']['last'] 'smith' >>> rec['job'] ['dev', 'mgr'] >>> rec['job'][-1] 'mgr' >>> rec['job'].append('ds') >>> rec {'name': {'first': 'bob', 'last': 'smith'}, 'job': ['dev', 'mgr', 'ds'], 'age': 40.5} >>> rec=0 >>> D={'a':1,'b':2,'c':3} >>> D {'a': 1, 'b': 2, 'c': 3} >>> ks=list(D.keys()) >>> ks ['a', 'b', 'c'] >>> ks.sort() >>> ks ['a', 'b', 'c'] >>> for key in ks:print(key,'=>',D[key])a => 1 b => 2 c => 3 >>> D {'a': 1, 'b': 2, 'c': 3} >>> for key in sorted(D):print(key,'=>',D[key])a => 1 b => 2 c => 3 >>> for c in 'dddssfg':print(c.upper())D D D S S F G >>> x=4 >>> while x >0:print('sdpd!'*x)x-=1sdpd!sdpd!sdpd!sdpd! sdpd!sdpd!sdpd! sdpd!sdpd! sdpd! >>> squares = [] >>> for x in [1,2,3,4,5]:squares.append(x ** 2)>>> squares [1, 4, 9, 16, 25] >>> squares = [x**2 for x in [1,2,3,4,5]] >>> squares [1, 4, 9, 16, 25] >>> D {'a': 1, 'b': 2, 'c': 3} >>> D['e']=99 >>> D {'a': 1, 'b': 2, 'c': 3, 'e': 99} >>> D['f'] Traceback (most recent call last):File "<pyshell#52>", line 1, in <module>D['f'] KeyError: 'f' >>> 'f' in D False >>> if not 'f' in D:print('missing')missing >>> value = D.get('x',0) >>> value 0 >>> value = D.get('a',0) >>> value 1 >>> value = D['x'] if 'x' in D else 0 >>> value 0可以看出:
1.字典不是序列,而是一種映射。映射是通過鍵而不是相對位置來存儲值。沒有可靠的從左至右的順序,簡單地將鍵映射到值。映射是一個對象集合,它具有可變性,可隨需求增大或減小。
2.可以通過鍵來對字典索引,讀取或改變鍵對應的值和序列類似,但方括號里面的是鍵而不是下標
3.字典的值能使用字典或鏈表作為嵌套。可以通過append擴展嵌入的列表。嵌套允許直接并輕松的建立復雜的信息結構。
4.python在最后一次引用對象后(比如賦值),這個對象占用的內(nèi)存空間將會自動清理掉。
5.由于字典沒有固定順序,所以當我們想要強調(diào)鍵的順序時,可以通過字典的keys方法收集一個鍵的列表,用列表的sort方法排序,然后用for循環(huán)輸出。也可以用sorted內(nèi)置函數(shù)
6.for循環(huán)可用在序列對象或字符串中,還有while循環(huán),不僅限于遍歷序列
7.迭代協(xié)議:一個在迭代操作情況下每次產(chǎn)生一個元素的對象。從左到右掃描一個對象的每個python工具都使用迭代協(xié)議。如果說一個對象在進行下一次循環(huán)之前先經(jīng)過一次內(nèi)置函數(shù)的作用,那么這就類似于解析表達式
8.獲取不存在的鍵值會出錯,因此為了避免錯誤的發(fā)生,我們可以通過if進行測試,in關系式允許我們查詢字典中一個鍵是否存在。還有其他的方法,比如get方法,有一個默認的值,如果不存在那個鍵,就輸出這個默認值。
5.元組
>>> T=(1,2,3,4,5) >>> len(T) 5 >>> T+(5,6) (1, 2, 3, 4, 5, 5, 6) >>> T (1, 2, 3, 4, 5) >>> T[0] 1 >>> T.index(4) 3 >>> T.count(4) 1 >>> T[0]=2 Traceback (most recent call last):File "<pyshell#8>", line 1, in <module>T[0]=2 TypeError: 'tuple' object does not support item assignment >>> T=('shfhf',222,[111,1,123]) >>> T[1] 222 >>> T[2][1] 1 >>> T.append(4) Traceback (most recent call last):File "<pyshell#12>", line 1, in <module>T.append(4) AttributeError: 'tuple' object has no attribute 'append'可以看出:
1.元組:不可改變的列表,編寫在圓括號中,支持任意類型,任意嵌套
2.元組的專有方法:index(a),查看a出現(xiàn)的下標,count(a),查看a出現(xiàn)的次數(shù)
3.不能通過append增長或縮短,因為它時不可變的
4.在程序中以列表的形式傳遞一個對象的集合,它可能隨時改變,但元組不會。因此我們有時會使用元組
6.文件
f = open('tt.txt','w') >>> f.write('hello\n') 6 >>> f.write('world\n') 6 >>> f.close() >>> f=open('tt.txt') >>> text=f.read() >>> text 'hello\nworld\n' >>> print(text) hello world>>> text.split() ['hello', 'world'] >>> dir(f) ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 'readline', 'readlines', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 'writelines'] >>> help(f.seek) Help on built-in function seek:seek(cookie, whence=0, /) method of _io.TextIOWrapper instanceChange stream position.Change the stream position to the given byte offset. The offset isinterpreted relative to the position indicated by whence. Valuesfor whence are:* 0 -- start of stream (the default); offset should be zero or positive* 1 -- current stream position; offset may be negative* 2 -- end of stream; offset is usually negativeReturn the new absolute position.可以看出:
1.文件對象時python對電腦外部文件的主要接口,要創(chuàng)建一個文件對象,需調(diào)用內(nèi)置的open函數(shù)以字符串形式傳給文件一個文件名和處理模式的字符串。文件對象提供了多種讀和寫的方法。
7.其他核心類型
>>> X=set('sshuds') >>> Y={'h','d'} >>> X,Y ({'u', 'd', 'h', 's'}, {'d', 'h'}) >>> X&Y {'d', 'h'} >>> X|Y {'h', 'u', 'd', 's'} >>> X-Y {'u', 's'} >>> {x**2 for x in [1,2,3,4]} {16, 1, 4, 9} >>> 1/3 0.3333333333333333 >>> (2/3)+(1/2) 1.1666666666666665 >>> import decimal >>> d=decimal.Decimal('3.14') >>> d+1 Decimal('4.14') >>> decimal.getcontext().prec = 2 >>> decimal.Decimal('1.00')/decimal.Decimal('3.00') Decimal('0.33') >>> from fractions import Fraction >>> f=Fraction(2,3) >>> f+1 Fraction(5, 3) >>> f+Fraction(1,2) Fraction(7, 6) >>> 1>2,1<2 (False, True) >>> bool('dff') True可以看出:
1.其他類型有:集合。集合是唯一的,不可變的對象的無序集合。可以通過內(nèi)置函數(shù)set創(chuàng)建,也可以通過集合常量和表達式創(chuàng)建。集合支持一般數(shù)學集合操作
2.固定精度浮點數(shù)類型:decimal。分數(shù)類型:fraction。布爾值類型
總結
以上是生活随笔為你收集整理的python基本对象类型的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java将属性练成字符串,Java中通过
- 下一篇: (斜率,点和线段)zzuli1196数星