python編程基礎(二)
- 序列簡介
- 字元串
- 列表
- 元組
6.11 標準類型操作符
標準類型操作符一般都能適用所有的序列類型。6.1.2序列類型操作符1.成員關係操作符(in、not in)成員關係操作符用來判斷一個元素是否屬於一個序列的。 in、not in 操作符的返回值一般來講就是True/False,滿足成員關係就返回True,否則就是False2.連接操作符(+)此操作符允許我們把一個序列和另一個相同類型的序列做連接。語法:sequence1+sequence2n
當你需要一個序列的多份拷貝的時候,重複操作符非常有用,語法如下:
sequence*copies_intn
>>> s=[0,1,2,3,4]n>>> s[:]n[0, 1, 2, 3, 4]n>>> s[0:3]n[0, 1, 2]n>>> s[:3]n[0, 1, 2]n>>> s[2:5]n[2, 3, 4]n>>> s[2:]n[2, 3, 4]n>>> s[1:3]n[1, 2]n>>> s[3]n3n>>> s[::]n[0, 1, 2, 3, 4]n
>>> s=abcdefghn>>> s[::-1]t#可以視作「翻轉」操作nhgfedcban>>> s[::2]t#隔一個取一個的操作nacegn
>>> s=[1,2,3,4,5,6,7]n>>> s[-100:100]n[1, 2, 3, 4, 5, 6, 7]n
每次把位於最後的一個字元砍掉。
>>> s=abcdefghijklmnn>>> i=-1n>>> for i in range(-1,-len(s),-1):nprint s[:i]nabcdefghijklmnabcdefghijklnabcdefghijknabcdefghijnabcdefghinabcdefghnabcdefgnabcdefnabcdenabcdnabcnabnan
>>> s=abcdefghijklmnn>>> for i in [None] + range(-1,-len(s),-1):nprint s[:i]nnabcdefghijklmnnabcdefghijklmnabcdefghijklnabcdefghijknabcdefghijnabcdefghinabcdefghnabcdefgnabcdefnabcdenabcdnabcnabnan
>>> for i in [None].extend(range(-1,-len(s),-1)):nprint s[:i]nnTraceback (most recent call last):nFile "<pyshell#28>", line 1, in <module>nfor i in [None].extend(range(-1,-len(s),-1)):nTypeError: NoneType object is not iterablen
python的for循環可以遍歷所有的可迭代類型,在(非純序列對象上)執行for循環時,就像在一個純序列對象上執行一樣。
1.類型轉換內建函數list()、str()、tuple()被用做在各種序列類型之間的轉換。這種類型轉換實際是工廠函數將對象作為參數將其內容拷貝到新生的對象中。序列類型轉換工廠函數- list(iter) 可迭代對象轉換列表
- str(obj) 把obj對象轉換為字元串(對象的字元串表示方法)
- unicode(obj) 把對象轉換為unicode字元串(使用默認編碼)
- basestring() 抽象工廠函數,其作用僅僅是為str、unicode函數提供父類,所以不能被實例化也不能被調用
- tuple(iter) 把一個可迭代對象轉換為一個元組對象
python為序列類型提供以下可操作的BIF。
注意:len()、reversed()、sum()函數只能接受序列類型對象作為參數,剩下的則還可以接受可迭代對象作為參數。max()、min()函數也可以接受一個參數列表序列類型可用的內建函數- enumerate(iter)tt接受一個可迭代的對象作為參數,返回一個enumerate 對象(同時也是一個迭代器),該對象生成由iter每個元素的index值和item值組成的元組
- len(seq)tttt返回seq的長度
- reverse(seq)ttt接受一個序列作為參數,返回一個逆序訪問的迭代器
- sum(seq,init=0)tt返回seq和可選參數init的總和,其效果等同於reduce(operator.add,seq,init)
- zip([it0,it1...itN])tt返回一個列表,其中第一個元素是it(),it1....這些元素組成的第一個元素組成的列表。
- sorted(iter,func)tt接受一個可迭代的對象作為參數,返回一個有序的列表
創建一個字元串就像使用一個標量一樣簡單,可以吧str()作為工廠方法來創建一個字元串並把它賦值給一個變數
>>> aString=Hello world!t#使用單引號n>>> anotherString="Python is cool!"t#使用雙引號n>>> print aStringnHello world!n>>> anotherStringnPython is cool!n>>> s=str(range(4))n>>> sn[0, 1, 2, 3]n
>>> aString=Hello world!n>>> aString[0]nHn>>> aString[1:5]nellon>>> aString[6:]nworld!n
>>> aString=aString[:6]+Python!n>>> aStringnHello Python!n>>> aString=different string altogethern>>> aStringndifferent string altogethern
>>> aString=Hello World!n>>> aString=aString[:3]+aString[4:]n>>> aStringnHelo World!n
>>> del aStringn>>> aStringn
>>> str1=abcn>>> str2=lmnn>>> str3=xyzn>>> str1<str2nTruen>>> str2!=str3nTruen>>> str1<str3 and str2==xyznFalsen
>>> aString=abcdn>>> len(aString)n4n>>> aString[0]nan>>> aString[1:3]nbcn>>> aString[2:4]ncdn>>> aString[4]nTraceback (most recent call last):nFile "<pyshell#16>", line 1, in <module>naString[4]nIndexError: string index out of rangen
使用不在本例範圍內的索引值都會報錯。
(2)反向索引反向索引時候,從-1開始,向字元串的開始方位計數,到字元串長度的負數為索引的結束。>>> aString=abcdn>>> -len(aString)n-4n>>> aString[-1]ndn>>> aString[-3:-1]nbcn>>> aString[-4]nan
>>> aString[2:]ncdn>>> aString[1:]nbcdn>>> aString[:-1]nabcn>>> aString[:]nabcdn
>>> bc in abcdnTruen>>> n in abcdnFalsen>>> nm not in abcdnTruen
#!usr/bin/env pythonnnimport stringnnalphas=string.letters+_nnums=string.digitsnnprint Welcome to the Identifier Checker v1.0nprint Testees must be at least 2 chars long.nmyInput=raw_input(Identifier to test)nnif len(myInput)>1:nn if myInput[0] not in alphasn print invalid:first symbol must be alphasn else:n for otherChar in myInput[1:]:nn if otherChar not in myInput[1:]:n print invalid:remaining symbols must be alphanumbericn breakn else:n print "okay as an identifier"n
>>> asndgfya+iwue9wqunasndgfyaiwue9wqun>>> hello++worldnhelloworldn>>> hello+ +worldnhello worldnn>>> s=Spanish+ +Inqusition+ +Made Easyn>>> snSpanish Inqusition Made Easyn>>> import stringn>>> string.upper(s[:3]+s[20])nSPAAn
>>> %s %s %(Spanish,Inquistion)nSpanish Inquistionn>>> s= .join((Spanish,Inqusition,Made Easy))n>>> snSpanish Inqusition Made Easyn>>> (%s%s %(s[:3],s[20])).upper()nSPAAn
>>> foo="Hello" world!n>>> foonHelloworld!n
>>> Hello+u +World+u!nuHello World!n>>> N!*3nN!N!N!n
>>> "%x"% 108n6cn>>> "%#x"% 108n0x6cn
>>> %f% 1234.56789n1234.567890n>>> %.2f%1234.56789n1234.57n>>> %E %1234.56789n1.234568E+03n>>> %g% 1234.56789n1234.57n>>> "%e" %(1111111111111111)n1.111111e+15n
>>> "%+d" % 4n+4n>>> "we are at %d%%" % 100nwe are at 100%n>>> "MM/DD/YY=%02d/%02d/%d"%(2,15,67)nMM/DD/YY=02/15/67n
>>> from string import Templaten>>> s=Template(There are ${howmany} ${lang} Quotation Symbols)n>>> print s.substitute(lang=Python,howmany=3)nThere are 3 Python Quotation Symbolsn>>> print s.substitute(lang=Python)nnTraceback (most recent call last):nFile "<pyshell#23>", line 1, in <module>nprint s.substitute(lang=Python)nFile "D:pylibstring.py", line 176, in substitutenreturn self.pattern.sub(convert, self.template)nFile "D:pylibstring.py", line 166, in convertnval = mapping[named]nKeyError: howmanyn>>> print s.safe_substitute(lang=Python)nThere are ${howmany} Python Quotation Symbolsn
>>> nnnn>>> print nnnn>>> rnnnn>>> print rnnnn
>>> str1=abcn>>> str2=lmnn>>> str3=xyzn>>> cmp(str1,str2)n-1n>>> cmp(str3,str1)n1n>>> cmp(str2,lmn)n0n
>>> str1=abcn>>> len(str1)n3n>>> len(Hello world!)n12n
>>> max(str2)nnn>>> min(str2)nln>>> min(ab12cd)n1n>>> max(ab12cd)ndn
>>> s=foobarn>>> for i,t in enumerate(s):nprint i,tnnn0 fn1 on2 on3 bn4 an5 rn
>>> s,t=foa,obrn>>> zip(s,t)n[(f, o), (o, b), (a, r)]n
>>> uer_name=raw_input("Enter your name: ")nEnter your name: Tomn>>> uer_namenTomn>>> len(uer_name)n3n
>>> chr(65)nAn>>> ord(a)n97n>>> ord(u2345)nnTraceback (most recent call last):nFile "<pyshell#2>", line 1, in <module>nord(u2345)nTypeError: ord() expected a character, but string of length 2 foundn>>> unichr(12345)nu?n
6.6 字元串內建函數
書上給出了很多很全。我摘錄幾個常用的。string.join(seq)tt以string作為分隔符,將seq中所有的元素合併為一個新的字元串。string.lower()ttt轉換string中所有大寫字元為小寫string.lstrip()ttt截掉string左邊的空格string.split(str="",num=string.count(str))以str為分隔符切片str,若num有指定值,則僅分隔num個子字元串string.upper()ttt轉換string中的小寫字母為大寫>>> quest=what is your favorite color?n>>> quest.count(or)n2n>>> :.join(quest.split())nwhat:is:your:favorite:color?n>>> quest.upper()nWHAT IS YOUR FAVORITE COLOR?n
>>> abc+defnabcdefn>>> s=abcn>>> s=s+abcn>>> snabcabcn
- 程序中出現字元串時一定要加個前綴u
- 不要用str()函數,用unicode()代替
- 不要使用過時的string模塊
- 不到必須時不要在你的程序裡面編解碼Unicode字元。
>>> alist=[123,abc,4.56]n>>> print alistn[123, abc, 4.56]n
>>> alist=[123,abc,4.56]n>>> print alistn[123, abc, 4.56]n>>> alist[0]n123n>>> alist[1:4]n[abc, 4.56]n>>> alist[:3]n[123, abc, 4.56]n>>> alist[:2]n[123, abc]nn3.如何更新列表n>>> alistn[123, abc, 4.56]n>>> alist[2]n4.56n>>> alist[2]=replacern>>> alistn[123, abc, replacer]n
>>> alistn[123, abc, replacer]n>>> del alist[1]n>>> alistn[123, replacer]n
>>> list1=[abc,123]n>>> list2=[xyz,789]n>>> list3=[abc,123]n>>> list1<list2nTruen>>> list2<list3nFalsen>>> list2>list3 and list1==list3nTruen
>>> num=[43,1.23,2,6.1e5]n>>> str_list=[jack,jumped,over]n>>> mix_list=[4,-1.9+6j,beef]n>>> num[1]n1.23n>>> num[:2]n[43, 1.23]n>>> str_list[2]novern>>> mix_list[1]n(-1.9+6j)n
>>> x in mix_listnFalsen>>> 4 in numnFalsen
>>> num+mix_listn[43, 1.23, 2, 610000.0, 4, (-1.9+6j), beef]n>>> str_list+mix_listn[jack, jumped, over, 4, (-1.9+6j), beef]n
>>> num*2n[43, 1.23, 2, 610000.0, 43, 1.23, 2, 610000.0]n>>> num*3n[43, 1.23, 2, 610000.0, 43, 1.23, 2, 610000.0, 43, 1.23, 2, 610000.0]n
>>> [i*2 for i in [8,-2,5]]n[16, -4, 10]n>>> [i for i in range(8) if i%2==0]n[0, 2, 4, 6]n
>>> list1,list2=[123,xyz],[456,abc]n>>> cmp(list1,list2)n-1n>>> cmp(list2,list1)n1n>>> list3=list2+[789]n>>> list3n[456, abc, 789]n>>> cmp(list2,list3)n-1n
>>> num=[43,1.23,2,6.1e5]n>>> len(num)n4n
>>> str_list=[jack,jumped,over,candestick]n>>> max(num)n610000.0n>>> min(num)n1.23n>>> max(str_list)novern>>> min(str_list)ncandestickn
>>> s=[Thry,stamp,them,when,"theyre",small]n>>> for t in reversed(s):nprint tnnnsmallntheyrenwhennthemnstampnThryn>>> sorted(s)n[Thry, small, stamp, them, "theyre", when]n
>>> for i,albums in enumerate(albums):nprint i,albumsnn0 tn1 an2 bn3 ln4 en5 sn>>> fn=[ian,stuart,david]n>>> ln=[bairnson,elliott,paton]n>>> n>>> for i,j in zip(fn,ln):nprint (%s%s %(i,j)).title()nnIanbairnsonnStuartelliottnDavidpatonn
>>> a=[6,4,5]n>>> sum(a)n15n>>> sum(a,10)n25n
>>> atuble=(123,abc,4.56)n>>> print atublen(123, abc, 4.56)n
>>> atuble[1:3]n(abc, 4.56)n>>> atuble[:3]n(123, abc, 4.56)n
>>> tup1=[12,34.56]n>>> tup2=[abc,xyz]n>>> tup3=tup1+tup2n>>> tup3n[12, 34.56, abc, xyz]n
>>> t=([xyz,123],23,-103.4)n>>> tn([xyz, 123], 23, -103.4)n>>> t[0][1]n123n>>> t[0][1]=[abc,def]n>>> tn([xyz, [abc, def]], 23, -103.4)n
>>> (x)nxn>>> (x,)n(x,)n>>> type (x)n<type str>n
- 映射類型:字典
- 操作符
- 內建函數
- 內建方法
- 字典的鍵
- 集合類型
- 操作符
- 內建函數『
- 內建方法
- 相關模塊
>>> dict1={}n>>> dict2={name:earth,port:80}n>>> dict1,dict2n({}, {name: earth, port: 80})n
>>> fdict=dict(([x,1],[y,2]))n>>> fdictn{y: 2, x: 1}n
>>> ddict={}.fromkeysn>>> ddict={}.fromkeys((x,y),-1)n>>> ddictn{y: -1, x: -1}n>>> edict={}.fromkeys((foo,bar))n>>> ddictn{y: -1, x: -1}n
>>> dict2={name:earth,port:80}n>>> for key in dict2.keys():nprint key=%s,value=%s %(key,dict2[key])nnnkey=name,value=earthnkey=port,value=80n
>>> dict2={name:earth,port:80}n>>> for key in dict2:nprint key=%s,value=%s %(key,dict2[key])nnnkey=name,value=earthnkey=port,value=80n
>>> dict2[name]nearthn
>>> dict3={}n>>> dict3[1]=abcn>>> dict3[1]=3.14159n>>> dict3[3.2]=xyzn>>> dict3n{1: 3.14159, 1: abc, 3.2: xyz}n
>>> dict3={1: 3.14159, 1: abc, 3.2: xyz}n>>> dict3n{1: 3.14159, 1: abc, 3.2: xyz}n
>>> dict2[name]=venusn>>> dict2[port]=6969n>>> dict2[arch]=sunos5n>>> dict2n{arch: sunos5, name: venus, port: 6969}n
>>> dict4={abc:123}n>>> dict5={abc:456}n>>> dict6={abc:123,97.3:83}n>>> dict7={xyz:123}n>>> dict4<dict5nTruen>>> dict4n{abc: 123}n>>> (dict4<dict6) and (dict4<dict7)nTruen>>> (dict5<dict6) and (dict5<dict7)nTruen>>> dict6<dict7nFalsen
>>> abc in dict4nTruen>>> name in dict4nFalsen
>>> dict(zip((x,y),(1,2)))n{y: 2, x: 1}n>>> dict([[x,1],[y,2]])n{y: 2, x: 1}n>>> dict([xy[i-1],i] for i in range(1,3))n{y: 2, x: 1}n>>> dict8=dict(x=1,y=2)n>>> dict9=dict(**dict8)n>>> dictn<type dict>n>>> dict9n{y: 2, x: 1}n>>> dict9=dict8.copynn>>> dict9=dict8.copy()n>>> dict9n{y: 2, x: 1}n
>>> dict9n{y: 2, x: 1}n>>> len (dict9)n2n
>>> hash([])nnTraceback (most recent call last):nFile "<pyshell#27>", line 1, in <module>nhash([])nTypeError: unhashable type: listn
>>> dict9n{y: 2, x: 1}n>>> dict9.keys()n[y, x]n>>> dict9.values()n[2, 1]n>>> dict9.items()n[(y, 2), (x, 1)]n
>>> dict10={f:123,f:xyz}n>>> dict10n{f: xyz}n>>> dict10[f]nxyzn
#!/usr/bin/env/pythonnndb=() #空資料庫初始化程序nndef newuser():nprompt=login desired:nwhile Ture:nname=raw_input(prompt)nif db.has_key(name):nprompt=name taken,try another:ncontinuenelse:nbreaknpwd=raw_input(passwd:)ndb[name]=pwdnndef olduser():nname=raw_input(login:)npwd=raw_input(passwd:)npasswd=bd.get(name)nif passwd==pwd:nprint welcome back,namenelse:nprint login incorrectnndef showmenu():nprompt=n
>>> s=set(cheeseshop)n>>> snset([c, e, h, o, p, s])n>>> t=frozenset(bookshop)n>>> tnfrozenset([b, h, k, o, p, s])n>>> type(s)n<type set>n>>> type(t)n<type frozenset>n>>> len(s)n6n>>> len(s)==len(t)nTruen>>> s==tnFalsen
>>> k in snFalsen>>> k in tnTruen>>> c not in snFalsen>>> for i in s:nprint inncnenhnonpnsn
>>> s.add(z)n>>> snset([c, e, h, o, p, s, z])n>>> s.update(pypi)n>>> snset([c, e, i, h, o, p, s, y, z])n>>> s.remove(z)n>>> snset([c, e, i, h, o, p, s, y])n>>> s-=set(pypi)n>>> snset([c, e, h, o, s])n
>>> t.add(z)nnTraceback (most recent call last):nFile "<pyshell#73>", line 1, in <module>nt.add(z)nAttributeError: frozenset object has no attribute addn
>>> del sn>>> snnTraceback (most recent call last):nFile "<pyshell#75>", line 1, in <module>nsnNameError: name s is not definedn
>>> s=set(cheeseshop)n>>> snset([c, e, h, o, p, s])n>>> s==tnFalsen>>> s!=tnTruen>>> u=frozenset(s)n>>> s==unTruen>>> set(posh)==set(shop)nTruen
>>> set(shop)<set(cheeseshop)nTruen>>> set(bookshop)>=set(shop)nTruen
>>> s|tnset([c, b, e, h, k, o, p, s])n
>>> s&tnset([h, s, o, p])n
3.差補/相對補集
兩個幾個的差補/相對補集指一個集合C,只屬於集合s,不屬於t>>> s-tnset([c, e])n
>>> s^tnset([b, e, k, c])n>>> t|snfrozenset([c, b, e, h, k, o, p, s])n>>> t^snfrozenset([c, b, e, k])n>>> t-snfrozenset([k, b])n
>>> s=set(u)n>>> snset([p, c, e, h, s, o])n>>> len(s)n6n
>>> set()nset([])n>>> set([])nset([])n>>> set(())nset([])n>>> set(shop)nset([h, s, o, p])n>>> frozenset([foo,bar])nfrozenset([foo, bar])n>>> f=open(number,w)n>>> for i in range(5):nf.write(%dn % i)nnn>>> f.close()n>>> f=open(number,r)n>>> set(f)nset([0n, 3n, 1n, 4n, 2n])n>>> f.close()n
- s.update(t) 用t中的元素修改s,s現在包含s或t的成員
- s.add(obj) 在集合s中添加對象obj
- s.remove(obj) 從集合對象中刪除對象obj
- s.discard(obj) 如果obj是集合s中的元素,從集合s中刪除對象obj
- s.pop() 刪除集合s中的任意一個對象,並返回它
- s.clear() 刪除集合s中所有對象
聲明:
以上學習筆記來自
《python核心編程》第2版 Wesley J.Chun 編著 宋吉廣譯 人民郵電出版社
推薦閱讀:
※相比於 Django、Pylon 等 Python 框架,Ruby on Rails 是否有很大的技術優勢?
※pycham如何整合pyqt5並安裝qtdesigner?
※怎樣用五十行Python代碼自造比特幣?
※為什麼Python類成員的調用和聲明必須有"this"?
TAG:Python |