




版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
可移植性:可以Windows和LinuxPythonPythonPythonPython程序在运行之前要先从源程序被编译成字节码,这样可以加快程序的运行速度。字节码由Python虚拟机执行(PVM。Python可以和.NETIronPython 的稳定版本Python。在Windows平台下,在Python项目下有一个IDLE程序,打开它之后会出现Python令行窗printprint o 2*22*2是2**10是!! # 将程序在文件.pyPython语句保存到后缀为.pycmdcmdpath/to/file.pypath/to/file.py>Windows下,直接双击.py文件执行程序,通常会闪过一个黑窗口,无法可以避免窗口Linuxprint'TheBrightSideofLife...' Anothercomment模块(Pythonimportmodule#without 注意,是不需要添加.pytop.pytest.pyimportprintimportprint有这么个模块,名字了……汗,把文件名改成myTest就没问题了。importprintimportprintfrommyTestimport testprint ', ', ', ', ', EmbeddingCals。书上举了一个C调用Python的简单示例:#include#includePy_Initialize(PyRun_SimpleString("x=brave+sir Dictionaries,字典:{'food':'spam','taste':'yum'}Tuple,元组:(1,'spam',4,'U')File文件:myfileopen('eggs其它类型:Sets,types,None,printprint3.14*2importmathprintmath.piimportprintprintprint##print)##strEN='springcomesandthefloweris printstrENprintstrEN[0]printstrEN[-1]printstrEN[0:5]#from0to4printstrEN[0:-1]printstrEN[0:]+*#String#StringprintstrEN.find('flower')printstrEN.re printstrEN.split('')printstrEN.upper()printstrEN.rstrip()#togethelp<p>HTMLCodegoes</div>"""importreresult=re.match('(\w+)',strEN)printresult.group(1)List#printtestList[1:]testList.append('i\'mnewprinttestList[-printtestList.pop(1)printlen(testList)printtestList#listmatrix=[[1,2,3],[4,5,[7,8,printmatrixcol2=[row[1]forrowinmatrix]#geta columnfromamatrixprintcol2col2even=[row[1]forrowinmatrix row[1]%2==0]#filteroddprintprinttestDict{'time':'时间','machine':'机器','timemachine':'时间机器'}printtestDict['time']#doitinanothernewDict={}printinPythonfromtherec={'name':{'first':'Bob','last': ['dev','mgr'], printrec=0 dwhenthelast referenceisgone#sortadictionaryD={'a':1,'b':2,'c':printforiinsorted(D):printiprint##optimazition:listcomprehension #优化:listcomprehensionforsquares=[x**2forxin[1,2,3,4,5]]printsquares#fasterthansquares=forxin[1,2,3,4,squares.append(x**2)printsquares#testifakeyexistinaifnotD.has_key('f'):printTupleslistnumberstringtestTupletestTuple=printsomeStr[0]someStr[0]=“//”printprintprint50.0//3#floorprint2+3jprintDecimalfromdecimalimportprintDecimal('1.0')+真为1,假为0print printprintTrue+2#Trueis1andFalseis和数字相关的模块有:math数学模块、random“等于”和“是”(==and#==#==testsifthetwo referequalL=M=printL==MprintLisM#istestsiftwovariablesreferthe testStrtestStr=testStr=\"\\在字符串前面加一个r,这种字符串叫做rawstring,表示本字符串不转义:myfile=open(r'C:\new\text.dat','w') Unicode如果要在字符串中Unicode的字符串,需要在字符串的前面加一个u。在普通字符串上执行unicode函数也可以将字符串转换为Unicode的。uniStruniStru'unicode的字符串'printuniStrprintuniStr[10]printstr(u'shouldbeASCII')#convert unicodestringtoASCIIprintunicode('goingtobe#string#string#error>>>print'addstrto '+print'addstrtonumber'+str(9) timeit#slice#sliceaprintuniStr[7:11]printuniStr[7:11:2]#onlyevencharprintprintuniStr[::-1]#righttoleftprintuniStr[::-2]#andoneeveryprintuniStr[7:11:-1]#whydoesn'titwork?printuniStr[11:7:-1]#because... sliceTestListsliceTestList=['echo.py','-a','- sliceTestList[1:]#willgettheASCII#convert#convertbetweenASCIIandprintord('d')#onlyworksononesingle printchr(97)#formatting#formattingprint"%s--%s--%s"% 3.14159,[1,2,)#dictionary#dictionarybasedprint'Mynameis%(name)sandI\'m%(age)s yearsold.'%{'name':'ChentestListtestList=[1,2,3,4,5]printtestListprinttestList*#number#numberofdeletedandinsertedneed testList[0:2]=[1,0,0,0]printtestListprinttestListprinttestListprintprintpopedItemtestList.pop(0)printtestListprintpopedItemdeltestList[0:4]printtestListtestList= #reference,#reference,nocot#testList= to#printnewTestList#iftestList testList[:]=#it#itwillaffectnewTestList#就会影响newTestListprintnewTestList#but testLististestList=#nothinghappensto #就不会影响newTestListprinttestDicttestDict= printkeyprintprintprinttestDict.get('name')#sameas #所有的keyprintprintprinttestDict.items()updateDictskill':'JavaSctipt'}print#注意key不使用引号括起来printdict(name='gaoshou')printdict([('name','ChenZhe'), printdict.fromkeys(['a','b'],testTupletestTuple=(1,4,0)printtestTuple#immutable,soifyouwanttosortatestTupleList=list(testTuple)sortedTupletuple(testTupleList)printPython数字(number)序列(sequence)(index、slice映射(map)可以使用key来索引(index#to#totestFile=codeStrdiv>','<p>',' open的时候制定'a'即为(append)模式,在这种模式下,文件的原有内容#to#totestFile=open('cainiao.txt','a')#to#totestFile=open('cainiao.txt','r')testStr=testFile.readline()printtestStrprinttestStr在文件中和恢复Python对使用Python的pickle模块,可以将Python对象直接在文件中,并且可testFiletestFile=open('pickle.txt','w')#andimportpickleimporttestDict= testFile=open('pickle.txt','r')printpickle.load(testFile)#binary#binarytestFile=open('cainiao.txt','wb')#wherewbmeanswriteandinbinaryimportstructbytes= testFiletestFile=open('cainiao.txt','rb')data=testFile.read()values=printC语言不同,Python的语句不需要用分号来结尾,而是由解释器按照换行printprintprinta=1;b=2;print ab=2a,b=printa,b#andprint#andthisiscalledsequencea,b,c,da,b,c,d=printa,b,c,dprintLL=[1,2,3,whilefront,L=L[0],printfront,没有#change#changethestdout#修改stdoutfromsysimporttemp=stdout #forlateruseoutputFile=open('out.txt','a')stdout=outputFilestdout.write('justatest')stdout= #restoretheoutputprintprint>>outputFile,'changedfor littlefromsysimportstderrPythonC语言对比(也就是说与大多数语言对比,Python的语法结构有一些不ifif语句中,代码块是按缩进的空格数量来判断的。也就是说空格数码块,当if的条件成立的时候它就会得到执行。#if#ifelifelsex=100ifprint'xishigh, printprint'andhighupinthesky!'elifx==50:print'xisprint'xis#logic#logicand,or,notifprint'xisTrue'ifxandy:print'xandyareallTrue'print'there\'sabadCif、else逻辑。例A=X?Y: PythonA=YifXelse whileC语言一样,Pythonbreakcontinue。而且还添加了一个elsewhile的判断的条件不成立的时候,不执行循环体,而是执行else中的代码块。x=5x=5 -=1#ifsomethingbad: #if #whenthewhileloopdoesn'texitwithbreakprint'finished!'forxx=foriinx:printprint#for#forinstring(andalsoinstring)x='Python'foriinprint#tuple#tuplefor for(a,b)inx:print #file#file tor,bestpracticetoreada#andalsothebestloopforlineinopen('test.txt'):printline.upper()testDict={'name':'ChenZhe','gender':'male'}forkeyintestDict:printkey+':'+testDict[key] torinlistcomprehension#listcomprehension中的迭代器testList=[lineforline print#basedoni tion#basedoni tionprotocoltestList=[9,8,7,6,5]printsorted(testList)#doesn'tchange printprintany(testList)#anyisTrueprintall(testList)#allareTrueprinttestList#tuple,list,andjoinallworkon tionprintprinttuple(open('test.txt'))#counterloop#counterloopforiinrange(5):printstr(i)+'isthecurrentprint'foriin str(i)+'isthecurrentvalue'print'foriinrange(2,9,2):#for(i=0;i<5;i++)printstr(i)+'isthecurrentvalue'print'zipL1L1=L2=printfor(a,b)inzip(L1,L2):print(a,b)L3=printzip(L1,L3)#extraitemsareignored#mapL1L3长度不一的时候,printmap(None,L1,L3)#'zip'adictionarykeys=['name','age']values=['ChenZhe',22]enumerate在循环的同时可以到当前的索引值#both#bothoffsetanditemtestStr='cainiao'for(offset,item)inprintitem,'appearsatPython是对接口编程,而不是对数据类型编程。例如我们定义了一个函数,在函数里用到了in这个接口,那么只要传入的参数实现了这个接口就可以,我们不在乎它是list还是tuple。returna+bprintmyAdd(4,5)L1,L2=[1,3,5],[2,4,6]print[myAdd(x,y)for(x,y)inglobal将变量的作用域扩大到文件globalgg=#outofthefuncionprint关键字调用函数(#keywordcallof#keyword#keywordcalloffunctiondefshow(a,b):printa,bprinta,b,c结合参数(#collecting在定义函数的时候可以使用*args指定在函数中使用元组的形式参数,使用**args来指定按照字典形式来使用参数:#collecting#collectingarguments#inatupleprintargs#in#inadictionaydefprintshowArgsDict(name=拆解参数(#unpackingprinta,b,c,dargs=#thisexampledoesn'tworkasthebookargsDict={'a':1,'b':2,'c':3,'d':4}#pass#passfunctionasadefminmax(test,*args):res=args[0]forarginiftest(arg,returnresdeflessthan(x,y):returnx<ydefgrtrthan(x,y):returnx>printminmax(lessthan,4,2,1,5,6,printminmax(grtrthan,4,2,1,5,6,lambda可以理解为一种小函数,但是它是一个表达式,而不是一个语句,所defadd(x,y):returnx+yprintadd(1,2)#lambdafunc=lambdax,y:x+yprintfunc(1,2)#defaultargumentinlambda#lambda函数中的默认函数func=lambdax,y=2:x+yprintfunc(1)#whydoweneed#lambda#a#alistoffunctionsL=[(lambdax:x**2),(lambdax: (lambdax:key=print{'already':(lambda:2+'got':(lambda:2*'one':(lambda:2**map有时候我们可以需要处理一个列表里的所有元素,可以使用一个for循环来Pythonmap函数可以帮我们的忙,它接受函数和列#map#mapfunction#basicsyntaxdefmul2(x):returnx*2testList=[1,2,3,4]printprintmap(lambdax:x*3,testList)#mapfunctionthathastwoargumentsdefmul(x,y):returnprintgenerator#basic#basicsyntax(afunctionthatyield)defgenMul2(N):foriinyieldi*foriingenMul2(5):print#insidefor,thenextmethodis#for循环的内部,Pythonnextx=printprint#print for循环、listcomprehensionmap testDict={'name':'Chen testIter=iter(testDict)printtestIter.next()printtestIter.next()#generatortestGen=(i*2foriin#testGenisageneratorprintdefselector():print =#selector()!!!!error!!!!assignmentinsidea makesit部变量。在上例中,XprintPythonmutable(可更改的)#mutable#mutabledefaultsdefsaver(x=[]):printsaver的时候,如果我们不提供一个xCstatic变量列表推导式(listcomprehension)listcomprehension,就是一种很方便的遍历方式。而且除了方便之外,速度通常也会比for循环高出许多。简单示例print[line.rstrip()forlineinopen('test.txt')]#usingif#listcomprehensionifprint[line.rstrip()forlineinopen('test.txt')if简单示例testListtestList=[1,2,3,4]defmul2(x):print[mul2(i)foriintestList]#addsomeiflogicprint if[mul2(i)foriintestListiflistcomprehension#nestedloopfor#nestedloopforxin[1,2,3]:foryin[1,2,3]:z=x*yprintstr(x)+'*'+str(y)+'is:printprint[x*yforxin[1,2,3]fory import totoseethemathprint'----------------importand importmathprintmath. #returna上面的代码引入了math模块,并且打印它的 包是一 (文件夹,package内必须有一个init.py文件,当其它importpackage的时候,这个文件会自动运行。假设的dir1中init.py内容如下:print'indir1print'indir1init'initX=98712xx=y=#它是在init.pyprint#from#fromdir1import#importdir1.testas 以使用字符串配合exec的方法import。例如:#importbystringmodname#importbystrin
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 基于因子分析法的绿地集团盈利质量研究
- 基于差分隐私机制的分布式优化算法研究
- 合股协议书范本合同范本
- 出租种菜棚子合同范本
- 商品转包合同范本
- 化肥委托检验合同范本
- 刷墙施工合同范例
- 非物质文化遗产在小学美术课程中的教学资源开发研究
- 商业美食摄影合同范本
- 个人饰品转卖合同范本
- 校园直饮水机供货安装及售后服务方案
- 废气处理系统改造及废水处理系统改造项目可行性研究报告
- 大学物业服务月考核评价评分表
- 现代家政导论-课件 1.1.2认识家政学起源与发展
- 期末模拟测试卷(试卷)2024-2025学年六年级数学上册人教版
- 2024届护士资格考试必考基础知识复习题库及答案(共170题)
- 工业大数据算法赛项实际操作部分评分细则变更说明
- 小学生防性侵安全教育主题班会课件
- DBT29-305-2024 天津市装配式建筑评价标准
- 背光异物改善8D
- 2024年五级咖啡师职业技能鉴定考试题库(含答案)
评论
0/150
提交评论