python函数中文手册_第1页
python函数中文手册_第2页
python函数中文手册_第3页
python函数中文手册_第4页
python函数中文手册_第5页
已阅读5页,还剩24页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、内置函数一,文档说明原始文档来自于pythonv2.7.2中文译文和用法尚不完全,您可以自由修改和完善,您可以在文档结尾鸣谢添上您的名字,我们将会感谢您做的贡献!二,函数列表1,取绝对值abs(x)Returntheabsolutevalueofanumber.Theargumentmaybeaplainorlongintegerorafloatingpointnumber.Iftheargumentisacomplexnumber,itsmagnitudeisreturned.如果你不知道绝对值什么意思,那就要补一下小学数学了!基本用法2,all(iterable)ReturnTrueifa

2、llelementsoftheiterablearetrue(oriftheiterableisempty).Equivalentto:3 .any(iterable)ReturnTrueifanyelementoftheiterableistrue.Iftheiterableisempty,returnFalse.Equivalentto:4 .basestring()Thisabstracttypeisthesuperclassforstrandunicode.Itcannotbecalledorinstantiated,butitcanbeusedtotestwhetheranobjec

3、tisaninstanceofstrorunicode.isinstance(obj,basestring)isequivalenttoisinstance(obj,(str,unicode).是字符串和字符编码的超类,是抽象类型。不能被调用或者实例化。可以用来判断实例是否为字符申或者字符编码。方法:5 .二进制转换bin(x)Convertanintegernumbertoabinarystring.TheresultisavalidPythonexpression.IfxisnotaPythonin£object,ithastodefineanindex()methodthatr

4、eturnsaninteger.转换成二进制表达方法:6 .布尔类型bool(x)ConvertavaluetoaBoolean,usingthestandardtruthtestingprocedure.Ifxisfalseoromitted,thisreturnsFalse;otherwiseitreturnsTrue.boolisalsoaclass,whichisasubclassofint.Classboolcannotbesubclassedfurther.ItsonlyinstancesareFalseandTrue布尔类型的转化用法:7 .二进制数组的转化bytearray(s

5、ource,encoding,errors)Returnanewarrayofbytes.Thebytearraytypeisamutablesequenceofintegersintherange0<=x<256.Ithasmostoftheusualmethodsofmutablesequences,describedinMutableSequenceTypes,aswellasmostmethodsthatthestrtypehas,seeStringMethodsTheoptionalsourceparametercanbeusedtoinitializethearrayi

6、nafewdifferentways:?Ifitisastring,youmustalsogivetheencoding(andoptionally,errors)parameters;bytearray()thenconvertsthestringtobytesusingstr.encode().?Ifitisaninteger,thearraywillhavethatsizeandwillbeinitializedwithnullbytes.?Ifitisanobjectconformingtothebufferinterface,aread-onlybufferoftheobjectwi

7、llbeusedtoinitializethebytesarray.?Ifitisaniterable,itmustbeaniterableofintegersintherange0<=x<256,whichareusedastheinitialcontentsofthearray.Withoutanargument,anarrayofsize0iscreated.8.callable(object)ReturnTrueiftheobjectargumentappearscallable,Falseifnot.Ifthisreturnstrue,itisstillpossiblet

8、hatacallfails,butifitisfalse,callingobjectwillneversucceed.Notethatclassesarecallable(callingaclassreturnsanewinstance);classinstancesarecallableiftheyhavea_call_()method.9.数字转化成字符chr(i)ReturnastringofonecharacterwhoseASCIIcodeistheintegeri.Forexample,chr(97)returnsthestring'a'.Thisistheinve

9、rseoford().Theargumentmustbeintherange0.255,inclusive;ValueErrorwillberaisedifiisoutsidethatrange.Seealsounichr().用法:10.classmethod(function)Aclassmethodreceivestheclassasimplicitfirstargument,justlikeaninstancemethodreceivestheinstance.Todeclareaclassmethod,usethisidiom:11 .两两比较cmp(x,y)Comparethetw

10、oobjectsxandyandreturnanintegeraccordingtotheoutcome.Thereturnvalueisnegativeifx<y,zeroifx=yandstrictlypositiveifx>y.X小于X输出负(-1),X等于Y输出零(0),X大于Y输出正(1)用法:12 .compile(source,filename,mode,flags,dont_inherit)CompilethesourceintoacodeorASTobject.Codeobjectscanbeexecutedbyanexecstatementorevaluated

11、byacalltoeval().sourcecaneitherbeastringoranASTobject.RefertotheastmoduledocumentationforinformationonhowtoworkwithASTplex(real,imag)Create a complex number with the valuereal+imag*jorconvertastringornumbertoacomplexnumber.Ifthefirstparameterisastring,itwillbeinterpretedasacomplexnumbe

12、randthefunctionmustbecalledwithoutasecondparameter.Thesecondparametercanneverbeastring.Eachargumentmaybeanynumerictype(includingcomplex).Ifimagisomitted,itdefaultstozeroandthefunctionservesasanumericconversionfunctionlikeint(),long()andfloat().Ifbothargumentsareomitted,returns0j.14 .delattr(object,n

13、ame)Thisisarelativeofsetattr().Theargumentsareanobjectandastring.Thestringmustbethenameofoneoftheobject'sattributes.Thefunctiondeletesthenamedattribute,providedtheobjectallowsit.Forexample,delattr(x,'foobar')isequivalenttodelx.foobar.15 .字典dict(arg)Createanewdatadictionary,optionallywith

14、itemstakenfromarg.ThedictionarytypeisdescribedinMappingTypesdict.Forothercontainersseethebuiltinlist,set,andtupleclasses,andthecollectionsmodule.16 .很重要的函数,属性输出dir(object)Withoutarguments,returnthelistofnamesinthecurrentlocalscope.Withanargument,attempttoreturnalistofvalidattributesforthatobject.方法1

15、7 .divmod(a,b)Taketwo(noncomplex)numbersasargumentsandreturnapairofnumbersconsistingoftheirquotientandremainderwhenusinglongdivision.Withmixedoperandtypes,therulesforbinaryarithmeticoperatorsapply.Forplainandlongintegers,theresultisthesameas(a/b,a%b).Forfloatingpointnumberstheresultis(q,a%b),whereqi

16、susuallymath.floor(a/b)butmaybe1lessthanthat.Inanycaseq*b+a%bisveryclosetoa,ifa%bisnon-zeroithasthesamesignasb,and0<=abs(a%b)<abs(b).18.enumerate(sequence,start=0)Returnanenumerateobject.sequencemustbeasequence,aniterator,orsomeotherobjectwhichsupportsiteration.Thenext()methodoftheiteratorretu

17、rnedbyenumerate()returns a tuple containing a count (fromstartwhichdefaultsto0)andthecorrespondingvalueobtainedfromiteratingoveriterable.enumerate。isusefulforobtaininganindexedseries:(0,seq0),(1,seq1),(2,seq2)19.eval(expression,globals,locals)Theargumentsareastringandoptionalglobalsandlocals.Ifprovi

18、ded,globalsmustbeadictionary.Ifprovided,localscanbeanymappingobject.Changedinversion2.4:formerlylocalswasrequiredtobeadictionary.20.execfile(filename,globals,locals)Thisfunctionissimilartotheexecstatement,butparsesafileinsteadofastring.Itisdifferentfromtheimportstatementinthatitdoesnotusethemodulead

19、ministrationitreadsthefileunconditionallyanddoesnotcreateanewmodule.和exec很相似的函数21.file(filename,mode,bufsize)Constructorfunctionforthefiletype,describedfurtherinsectionFileObjects.Theconstructor'sargumentsarethesameasthoseoftheopen()built-infunctiondescribedbelow.Whenopeningafile,it'sprefera

20、bletoouse)insteadofinvokingthisconstructordirectly.fileismoresuitedtotypetesting(forexample,writingisinstance(f,file).filter(function,iterable)Constructalistfromthoseelementsofiterableforwhichfunctionreturnstrue.iterablemaybeeitherasequence,acontainerwhichsupportsiteration,oraniterator.Ifiterableisa

21、stringoratuple,theresultalsohasthattype;otherwiseitisalwaysalist.IffunctionisNone,theidentityfunctionisassumed,thatis,allelementsofiterablethatarefalseareremoved.Notethatfilter(function,iterable)isequivalenttoitemforiteminiterableiffunction(item)iffunctionisnotNoneanditemforiteminiterableifitemiffun

22、ctionisNone.Seeitertools.ifilter()anditertools.ifilterfalse()foriteratorversionsofthisfunction,includingavariationthatfiltersforelementswherethefunctionreturnsfalse.23.浮点数值转化float(x)用法:format(value,format_spec)Convertavaluetoa“formatted“reeepntation,ascontrolledbyformat_spec.Theinterpretationofforma

23、t_specwilldependonthetypeofthevalueargument,howeverthereisastandardformattingsyntaxthatisusedbymostbuilt-intypes:FormatSpecificationMini-Language.25 frozenset(iterable)Returnafrozensetobject,optionallywithelementstakenfromiterable.ThefrozensettypeisdescribedinSetTypesset,frozenset.For other containe

24、rs see the built indict,list,andtupleclasses,andthecollectionsmodule.26 .getattr(object,name,default)Rmustbeastring.Ifthestringisthenameofoneoftheobject'sattributes,theresultisthevalueofthatattribute.Forexample,getattr(x,'foobar')isequivalentt

25、ox.foobar.Ifthenamedattributedoesnotexist,defaultisreturnedifprovided,otherwiseAttributeErrorisraised.27 .全局参数globals()Returnadictionaryrepresentingthecurrentglobalsymboltable.Thisisalwaysthedictionaryofthecurrentmodule(insideafunctionormethod,thisisthemodulewhereitisdefined,notthemodulefromwhichiti

26、scalled).hasattr(object,name)Returnthehashvalueoftheobject(ifithasone).Hashvaluesareintegers.Theyareusedtoquicklycomparedictionarykeysduringadictionarylookup.Numericvaluesthatcompareequalhavethesamehashvalue(eveniftheyareofdifferenttypes,asisthecasefor1and1.0).29.hash(object)Returnthehashvalueoftheo

27、bject(ifithasone).Hashvaluesareintegers.Theyareusedtoquicklycomparedictionarykeysduringadictionarylookup.Numericvaluesthatcompareequalhavethesamehashvalue(eveniftheyareofdifferenttypes,asisthecasefor1and1.0).30. 很重要的帮助函数方法help(object)31. 十六进制转化hex(x)Convertanintegernumber(ofanysize)toahexadecimalstr

28、ing.TheresultisavalidPythonexpression.用法:32. 内存地址id(object)Returnthe“identity“ofanobject.Thisisaninteger(orlonginteger)whichisguaranteedtobeuniqueandconstantforthisobjectduringitslifetime.Twoobjectswithnon-overlappinglifetimesmayhavethesameid()value.如果想知道某个对象的内存地址,用这个内置函数,返回的是10进制的地址。33.input(prompt

29、)Equivalenttoeval(raw_input(prompt).34.int(x,base)Convertastringornumbertoaplaininteger.Iftheargumentisastring,itmustcontainapossiblysigneddecimalnumberrepresentableasaPythoninteger,possiblyembeddedinwhitespace.Thebaseparametergivesthebasefortheconversion(whichis10bydefault)andmaybeanyintegerinthera

30、nge2,36,orzero.Ifbaseiszero,theproperradixisdeterminedbasedonthecontentsofstring;theinterpretationisthesameasforintegerliterals.(SeeNumericliterals.)Ifbaseisspecifiedandxisnotastring,TypeErrorisraised.Otherwise,theargumentmaybeaplainorlongintegerorafloatingpointnumber.Conversionoffloatingpointnumber

31、stointegerstruncates(towardszero).Iftheargumentisoutsidetheintegerrangealongobjectwillbereturnedinstead.Ifnoargumentsaregiven,returns0.35.isinstance(object,classinfo)Returntrueiftheobjectargumentisaninstanceoftheclassinfoargument,orofa(directorindirect)subclassthereof.Alsoreturntrueifclassinfoisatyp

32、eobject(new-styleclass)andobjectisanobjectofthattypeorofa(directorindirect)subclassthereof.Ifobjectisnotaclassinstanceoranobjectofthegiventype,thefunctionalwaysreturnsfalse.Ifclassinfoisneitheraclassobjectnoratypeobject,itmaybeatupleofclassortypeobjects,ormayrecursivelycontainothersuchtuples(otherse

33、quencetypesarenotaccepted).Ifclassinfoisnotaclass,type,ortupleofclasses,types,andsuchtuples,aTypeErrorexceptionisraised.36.issubclass(class,classinfo)Returntrueifclassisasubclass(directorindirect)ofclassinfo.Aclassisconsideredasubclassofitself.classinfomaybeatupleofclassobjects,inwhichcaseeveryentry

34、inclassinfowillbechecked.Inanyothercase,aTypeErrorexceptionisraised.37. 导管,窗口,容器,数据的窗口化iter(o,sentinel)Returnaniteratorobject.Thefirstargumentisinterpretedverydifferentlydependingonthepresenceofthesecondargument.Withoutasecondargument,omustbeacollectionobjectwhichsupportstheiterationprotocol(theiter

35、()method),oritmustsupportthesequenceprotocol(thegetitem()methodwithintegerargumentsstartingat0).Ifitdoesnotsupporteitherofthoseprotocols,TypeErrorisraised.Ifthesecondargument,sentinel,isgiven,thenomustbeacallableobject.Theiteratorcreatedinthiscasewillcallowithnoargumentsforeachcalltoitsnext()method;

36、ifthevaluereturnedisequaltosentinel,StopIterationwillberaised,otherwisethevaluewillbereturned.iter(o,sentinel)返回一个迭代器对象。第一个参数根据第二个参数进行编译。第二参数为空,。必须是支持迭代器的协议(the_iter_()method)的集合对象,或者支持顺序协议(the_getitem_()methodwithintegerargumentsstaringat0).如果不支持其中任意一种协议,程序将会抛出类型异常。假如第二个参数被给出,然后O必须是一个可被调用的对象。迭代器被创建

37、万一will掉用Owith没有参数foreachcalltoitsnext()method;如果返回值和初始值相同l,StopIteration将会抛出,否则值会被返回!38. 计算长度(常用函数)len(s)Returnthelength(thenumberofitems)ofanobject.Theargumentmaybeasequence(string,tupleorlist)oramapping(dictionary).用法:39. 转化成列表list(iterable)Returnalistwhoseitemsarethesameandinthesameorderasiterabl

38、e'sitems.iterablemaybeeitherasequence,acontainerthatsupportsiteration,oraniteratorobject.Ifiterableisalreadyalist,acopyismadeandreturned,similartoiterable:.Forinstance,list('abc')returns'a','b','c'andlist(1,2,3)returns1,2,3.Ifnoargumentisgiven,returnsanewemptylist

39、,.40.locals()Updateandreturnadictionaryrepresentingthecurrentlocalsymboltable.Freevariablesarereturnedbylocals()whenitiscalledinfunctionblocks,butnotinclassblocks.Updateandreturnadictionary更新和返回字典long(x,base)Convertastringornumbertoalonginteger.Iftheargumentisastring,itmustcontainapossiblysignednumb

40、erofarbitrarysize,possiblyembeddedinwhitespace.Thebaseargumentisinterpretedinthesamewayasforint(),andmayonlybegivenwhenxisastring.Otherwise,theargumentmaybeaplainorlongintegerorafloatingpointnumber,andalongintegerwiththesamevalueisreturned.Conversionoffloatingpointnumberstointegerstruncates(towardsz

41、ero).Ifnoargumentsaregiven,returns0L.42 .map(function,iterable,.)Applyfunctiontoeveryitemofiterableandreturnalistoftheresults.Ifadditionaliterableargumentsarepassed,functionmusttakethatmanyargumentsandisappliedtotheitemsfromalliterablesinparallel.Ifoneiterableisshorterthananotheritisassumedtobeexten

42、dedwithNoneitems.IffunctionisNone,theidentityfunctionisassumed;iftherearemultiplearguments,map()returnsalistconsistingoftuplescontainingthecorrespondingitemsfromalliterables(akindoftransposeoperation).Theiterableargumentsmaybeasequenceoranyiterableobject;theresultisalwaysalist.43 .最大值max(iterable,ar

43、gs.,key)Withasingleargumentiterable,returnthelargestitemofanon-emptyiterable(suchasastring,tupleorlist).Withmorethanoneargument,returnthelargestofthearguments.Theoptionalkeyargumentspecifiesaone-argumentorderingfunctionlikethatusedforlist.sort().Thekeyargument,ifsupplied,mustbeinkeywordform(forexamp

44、le,max(a,b,c,key=func).44 .memoryview(obj)Returna“memoryview"objectcreatedfromthegivenargument.Seememoryviewtypeformoreinformation.45 .最小值min(iterable,args儿key)Withasingleargumentiterable,returnthesmallestitemofanon-emptyiterable(suchasastring,tupleorlist).Withmorethanoneargument,returnthesmall

45、estofthearguments.46 .迭代以后的函数next(iterator,default)Retrievethenextitemfromtheiteratorbycallingitsnext()method.Ifdefaultisgiven,itisreturnediftheiteratorisexhausted,otherwiseStopIterationisraised.用法:object()Returnanewfeaturelessobject.objectisabaseforallnewstyleclasses.Ithasthemethodsthatarecommontoa

46、llinstancesofnewstyleclasses.48 .八进制字符串的转化oct(x)Convertanintegernumber(ofanysize)toanoctalstring.TheresultisavalidPythonexpression.用法:49 .open(filename,mode,bufsize)Openafile,returninganobjectofthefiletypedescribedinsectionFileObjects.Ifthefilecannotbeopened,IOErrorisraised.Whenopeningafile,it's

47、preferpenOouseinsteadofinvokingthefileconstructordirectly.50 .字符转化成ASCn码ord(c)Givenastringoflengthone,returnanintegerrepresentingtheUnicodecodepointofthecharacterwhentheargumentisaunicodeobject,orthevalueofthebytewhentheargumentisan8-bitstring.Forexample,ord('a')returnstheinteger97,ord(u'

48、;u2020')returns8224.Thisistheinverseofchr()for8-bitstringsandofunichr()forunicodeobjects.IfaunicodeargumentisgivenandPythonwasbuiltwithUCS2Unicode,thenthecharacter'scodepointmustbeintherange0.65535inclusive;otherwisethestringlengthistwo,andaTypeErrorwillberaised.pow(x,y,z)Returnxtothepowery;

49、ifzispresent,returnxtothepowery,moduloz(computedmoreefficientlythanpow(x,y)%z).Thetwo-argumentformpow(x,y)isequivalenttousingthepoweroperator:x*y.52. print函数原来本身就是函数。print(object,.,sep='',end='n',file=sys.stdout)Printobject(s)tothestreamfile,separatedbysepandfollowedbyend.sep,endandf

50、ile,ifpresent,perty(fget,fset,fdel,doc)Returnapropertyattributefornew-styleclasses(classesthatderivefromobject).54.range(start,stop,step)起始位置,终止位置,步长55.raw_input(prompt)Ifthepromptargumentispresent,itiswrittentostandardoutputwithoutatrailingnewline.用法:56.reduce(fu

51、nction,iterable,initializer)Applyfunctionoftwoargumentscumulativelytotheitemsofiterable,fromlefttoright,soastoreducetheiterabletoasinglevalue.Forexample,reduce(lambdax,y:x+y,1,2,3,4,5)calculates(1+2)+3)+4)+5).Theleftargument,x,istheaccumulatedvalueandtherightargument,y,istheupdatevaluefromtheiterabl

52、e.Iftheoptionalinitializerispresent,itisplacedbeforetheitemsoftheiterableinthecalculation,andservesasadefaultwhentheiterableisempty.Ifinitializerisnotgivenanditerablecontainsonlyoneitem,thefirstitemisreturned.57. 重载模块,很重要的函数reload(module)58.repr(object)Returnastringcontainingaprintablerepresentation

53、ofanobject.Thisisthesamevalueyieldedbyconversions(reversequotes).Itissometimesusefultobeabletoaccessthisoperationasanordinaryfunction.Formanytypes,thisfunctionmakesanattempttoreturnastringthatwouldyieldanobjectwiththesamevaluewhenpassedtoeval(),otherwisetherepresentationisastringenclosedinanglebrack

54、etsthatcontainsthenameofthetypeoftheobjecttogetherwithadditionalinformationoftenincludingthenameandaddressoftheobject.Aclasscancontrolwhatthisfunctionreturnsforitsinstancesbydefiningarepr()method.59 .reversed(seq)Returnareverseiterator.seqmustbeanobjectwhichhasareversed()methodorsupportsthesequencep

55、rotocol(thelen()methodandthegetitem()methodwithintegerargumentsstartingat0).60 .round(x,n)Returnthefloatingpointvaluexroundedtondigitsafterthedecimalpoint.Ifnisomitted,itdefaultstozero.Theresultisafloatingpointnumber.Valuesareroundedtotheclosestmultipleof10tothepowerminusn;iftwomultiplesareequallycl

56、ose,roundingisdoneawayfrom0(so.forexample,round(0.5)is1.0andround(-0.5)is-1.0).61 .去重,但是不改变原始数据set(iterable)iterable . The set type is described inReturnanewset,optionallywithelementstakenfromSetTypesset,frozenset.62 .setattr(object,name,value)Thisisthecounterpartofgetattr().Theargumentsareanobject,

57、astringandanarbitraryvalue.Thestringmaynameanexistingattributeoranewattribute.Thefunctionassignsthevaluetotheattribute,providedtheobjectallowsit.Forexample,setattr(x,'foobar',123)isequivalenttox.foobar=123.63 .切片起始位置,终止位置,步长slice(start,stop,step)Returnasliceobjectrepresentingthesetofindicess

58、pecifiedbyrange(start,stop,step).ThestartandstepargumentsdefaulttoNone.Sliceobjectshaveread-onlydataattributesstart,stopandstepwhichmerelyreturntheargumentvalues(ortheirdefault).Theyhavenootherexplicitfunctionality;howevertheyareusedbyNumericalPythonandotherthirdpartyextensions.Sliceobjectsarealsogeneratedwhene

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论