FAFU机器学习 01asicsfython中文_第1页
FAFU机器学习 01asicsfython中文_第2页
FAFU机器学习 01asicsfython中文_第3页
FAFU机器学习 01asicsfython中文_第4页
FAFU机器学习 01asicsfython中文_第5页
已阅读5页,还剩94页未读 继续免费阅读

下载本文档

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

文档简介

内容Python线性回归分类的线性模型决策树kNN和Bayes支持向量机集成学习聚类方法强化学习人工神经网络机器学习的应用python()基础知识安装,使用和功能数据和操作控制流功能模块数据结构…2020/12/3机器学习基础第1-5课安装(Python)在Windows(Windows)上安装访问/downloads/并下载最新版本。安装就像任何其他基于Windows的软件一样使用anacondaAnaconda是一个开源的包、环境管理器,可以用于在同一个机器上安装不同版本的软件包及其依赖,并能够在不同的环境之间切换Anaconda包括Conda、Python以及一大堆安装好的工具包,比如:numpy、pandas等/2020/12/3机器学习基础第1-6课使用解释器提示符()打印(“HelloWorld”)选择编辑器编辑源文件()并使用源文件(在命令行中运行)编辑源文件并将其保存为。py打开终端窗口将目录更改为保存文件的位置,例如cd/tmp/py通过输入命令pythonhello.py运行程序。使用IDLE(集成开发和学习环境)2020/12/3机器学习基础第1-7课Python的特性Python(Python)的特性简单()易学()免费开放源码(,)高级语言()可移植性()解释()面向对象()可扩展()可嵌入()扩展库()2020/12/3机器学习基础第1-8课基础知识注释()注释是#符号右边的任何文本,主要作为程序读者的注释#注意,print是一条语句打印('HelloWorld')在程序中尽可能多地使用有用的注释:解释假设解释重要的决定解释重要的细节解释你要解决的问题解释你在程序中试图克服的问题,等等2020/12/3机器学习基础第1-9课Numbers(数)IntegersFloatsStrings(字符串):不可变单引号双引号三引号使用三引号-(“”“或”'')指定多行字符串。2020/12/3机器学习基础第1-10课format方法Savethefollowinglinesasafilestr_format.py:if__name__=='__main__':age=20name='Swaroop'print('{0}was{1}yearsold'.format(name,age))print('Whydoes{0}usepython?'.format(name))2023/11/4FoundationsofMachineLearningLesson1-8Swaroopwas20yearsoldWhydoesSwaroopusepython?Comparewith:Name+“was“+str(age)+“yearsold.”Thenumbersareoptionalage=20name='Swaroop'print('{}was{}yearsold'.format(name,age))print('Whydoes{}usepython?'.format(name))Morespecifications

#decimal(.)precisionof3forfloat(0.333)print('{0:.3f}'.format(1.0/3))

#fillwithunderscores(_)withthetextcentered#(^)to1111width'___hello___'print('{0:_^11}'.format('hello'))

#keywordbasedprint('Whydoes{xm}usepython?'.format(xm='tom'))EscapeSequences'What\'syourname?''Thisisthefirstline\nThisisthesecondline'"Thisisthefirstsentence.\Thisis

thesecondsentence."RawStringr"Newlinesareindicatedby\n"2023/11/4FoundationsofMachineLearningLesson1-11变量变量正是这个名字所暗示的——它们的值可以变化标识符命名标识符的第一个字符必须是字母表中的字母或下划线()。标识符名称的其余部分可以由字母、下划线(Uu)或数字(0-9)组成。标识符名称区分大小写。IdentifierNaming(标识符命名法)逻辑和物理线路当你写程序时看到的是物理程序。逻辑行是Python将其视为单个语句的内容。Python隐式地假设每个物理行对应于一个逻辑行。缩进(前进)空白在Python中很重要。实际上,行首的空白很重要。这叫做缩进。逻辑行开头的前导空格(空格和制表符)用于确定逻辑行的缩进级别,而缩进级别又用于确定语句的分组。这意味着放在一起的语句必须有相同的缩进。每一组这样的语句被称为一个块。i=5#Errorbelow!print('Valueis',i)print('Irepeat,thevalueis',i)OperatorsandExpressions(操作符和表达式)Operators(操作符)+(plus--加)Addstwoobjects3+5gives8.'a'+'b'gives'ab'.-(minus—减)给出一个数与另一个数的减法;如果第一个操作数不存在,则假定它为零。-5.2:得出一个负数,50-24给出26*(multiply—乘)给出两个数的乘法或返回重复多次的字符串。2*3等于6la'*3表示“lalala”。**(power—乘方)Returnsxtothepowerofy3**4gives81(i.e.3*3*3*3)/(divide—除)Dividexbyy13//3gives413/3gives4.333333333333333%(modulo—取余)Returnstheremainderofthedivision13%3gives1.-25.5%2.25gives1.5.<<(leftshift—左移) 按指定的位数向左移动数字的位。(每个数字在存储器中用位或二进制数字表示,即0和1)2<<2等于8。2用10位表示。左移2位得到代表十进制8的1000。>>(rightshift—右移)按指定的位数将数字的位右移。11>>1gives5.11用1011表示,当右移1位时,1011给出101,即十进制数5。5:1013:011&(bit-wiseAND—按为与)Bit-wiseANDofthenumbers5&3gives1.换成二进制,同一为一|(bit-wiseOR—按位或)BitwiseORofthenumbers5|3gives7有一为一,否则为0^(bit-wiseXOR—按位异或)BitwiseXORofthenumbers相同为0,否则为15^3gives6~(bit-wiseinvert—按位逆转)按位取反Thebit-wiseinversionofxis-(x+1)~5gives-6.5:00000000000000000000000000000101 ~5:11111111111111111111111111111010<(lessthan—小于)Returnswhetherxislessthany.AllcomparisonoperatorsreturnTrueorFalse.Notethecapitalizationofthesenames.5<3givesFalseand3<5givesTrue.Comparisonscanbechainedarbitrarily:3<5<7givesTrue.>(greaterthan—大于)Returnswhetherxisgreaterthany5>3returnsTrue.Ifbothoperandsarenumbers,theyarefirstconvertedtoacommontype.Otherwise,italwaysreturnsFalse.<=(lessthanorequalto—小于或者等于)Returnswhetherxislessthanorequaltoyx=3;y=6;x<=yreturnsTrue.>=(greaterthanorequalto大于或者等于)Returnswhetherxisgreaterthanorequaltoyx=4;y=3;x>=3returnsTrue.==(equalto—等于)Comparesiftheobjectsareequalx=2;y=2;x==yreturnsTrue.x='str';y='stR';x==yreturnsFalse.x='str';y='str';x==yreturnsTrue.!=(notequalto—不等于)Comparesiftheobjectsarenotequalx=2;y=3;x!=yreturnsTrue.not(booleanNOT—非)IfxisTrue,itreturnsFalse.IfxisFalse,itreturnsTrue.x=True;notxreturnsFalse.and(booleanAND—与)如果x为False,x和y返回False,否则返回y的求值x=False;y=True;x和y返回False,因为x为False。在这种情况下,Python不会计算y,因为它知道“and”表达式的左侧为False,这意味着无论其他值如何,整个表达式都将为False。这称为短路评估。or(booleanOR—或)IfxisTrue,itreturnsTrue,elseitreturnsevaluationofyx=True;y=False;xoryreturnsTrue.Short-circuitevaluationapplieshereaswell.orandnotin,notin,is,isnot,<,<=,>,>=,!=,==|^&<<,>>+,-*,/,//,%+x,-x,~x**x[index],x(arguments),x.atribute(exps…),[exps…],{key:value…}EvaluationOrderControlFlowTheifstatementThewhileStatementTheforloopThebreakStatementThecontinueStatementTheifstatementifcondition:statementselifcondition:statementselse:statements编写一个程序,要求用户输入一个100分制的成绩,程序输出相应A、B、C和D的表示:大于或者等于90分:A大于或者等于80分,同时小于90分:B大于或者等于60分,同时小于80分:C小于60分:D2023/11/4FoundationsofMachineLearningLesson1-26ThewhileStatementwhilecondition:statements2023/11/4FoundationsofMachineLearningLesson1-27控制循环运行的3种方式固定次数与用户进行交互方式设置特殊值的方式例如:编写一个统计课程平均成绩的程序2023/11/4FoundationsofMachineLearningLesson1-28编写一个程序,用来估算pi的值。

importrandomrandom.random()2023/11/4FoundationsofMachineLearningLesson1-29编写一个程序,输出前50个素数,输出时每5个数一行2023/11/4FoundationsofMachineLearningLesson1-30TheforloopAboutrange(intfrom,intto,intstep)range返回从第一个数字到第二个数字的数字序列。例如,range(1,5)给出了序列[1,2,3,4]。默认情况下,range的步数为1。如果我们提供第三个数字的范围,那么这就是步数。例如,range(1,5,2)给出[1,3]。请记住,范围扩展到第二个数字,即不包括第二个数字。for<var>in<iterable>:<statement(s)>else:

<statement(s)>

2023/11/4FoundationsofMachineLearningLesson1-31编写一个程序,输出乘法口诀表2023/11/4FoundationsofMachineLearningLesson1-32ThebreakStatement2023/11/4FoundationsofMachineLearningLesson1-33if__name__=="__main__":foriinrange(1,5):ifi%2==0:breakprint(i)else:print("forloopisover")ThecontinueStatement2023/11/4FoundationsofMachineLearningLesson1-34if__name__=="__main__":foriinrange(1,5):ifi%2==0:continueprint(i)else:print("forloopisover")Functions使用def关键字定义函数。在这个关键字后面是函数的标识符名称,后面是一对圆括号(可能包含一些变量的名称),最后一个冒号是行尾的冒号。接下来是作为该函数一部分的语句块。2023/11/4FoundationsofMachineLearningLesson1-35def

say_hello():

#blockbelongingtothefunction

print('helloworld‘)#Endoffunctionsay_hello()#callthefunctionsay_hello()#callthefunctionagainFunctionParameters(函数的参数)2023/11/4FoundationsofMachineLearningLesson1-36def

print_max(a,b):

ifa>b:

print(a,'ismaximum‘)

elifa==b:

print(a,'isequalto',b)

else:

print(b,'ismaximum‘)

LocalVariables(局部变量)当您在函数定义内声明变量时,它们与函数外部使用的同名变量没有任何关系,即变量名是函数的局部名称。这称为变量的范围。所有变量都有从名称定义开始声明的块的范围。2023/11/4FoundationsofMachineLearningLesson1-37x=50def

func(x):

print('xis',x)x=2

print('Changedlocalxto',x)

func(x)print('xisstill',x)2023/11/4FoundationsofMachineLearningLesson1-38x=50def

func(x):

print('xis',x)x=2

y=10

print('Changedlocalxto',x)

func(x)Print('xisstill',x)Print(y)Theglobalstatement(全局语句)2023/11/4FoundationsofMachineLearningLesson1-39x=50def

func():

globalx

print('xis',x)x=2

print('Changedglobalxto',x)

func()Print('Valueofxis',x)DefaultArgumentValues(参数的缺省值):就是在声明函数的某个参数的时候为之指定一个默认值,在调用该函数的时候如果采用该默认值,你就无须指定该参数。2023/11/4FoundationsofMachineLearningLesson1-40def

say(message,times=1):

print(message*times)say('Hello')say('World',5)KeywordArguments(命名实参):可以按照参数的名称传递参数2023/11/4FoundationsofMachineLearningLesson1-41def

func(a,b=5,c=10):

print('ais',a,'andbis',b,'andcis',c)func(3,7)func(25,c=24)func(c=50,a=100)VarArgsparameters(变长参数)=>*param(一个星号),将多个参数收集到一个’元组’对象中;=>**param(两个星号),将多个参数收集到一个’字典’对象中;2023/11/4FoundationsofMachineLearningLesson1-42def

total(initial=5,*numbers,**keywords):count=initial

fornumberinnumbers:count+=number

forkeyinkeywords:count+=keywords[key]

returncountPrint(total(10,1,2,3,shapes=50,fruits=100))Thereturnstatement(返回语句)Thereturnstatementisusedtoreturnfromafunctioni.e.breakoutofthefunction.Wecanoptionallyreturnavaluefromthefunctionaswell.return语句用于从函数返回,即从函数中中断。我们也可以选择从函数返回一个值。returnNone2023/11/4FoundationsofMachineLearningLesson1-43DocStrings(文档字符串):打印“”“中的注释语句2023/11/4FoundationsofMachineLearningLesson1-44def

print_max(x,y):

'''Printsthemaximumoftwonumbers.Thetwovaluesmustbeintegers.'''

#converttointegers,ifpossiblex=int(x)y=int(y)

ifx>y:

print(x,'ismaximum‘)

else:

print(y,'ismaximum‘)

print_max(3,5)print(print_max.__doc__)编写一个程序,输出前50个素数,输出时每5个数一行2023/11/4FoundationsofMachineLearningLesson1-45密码必须满足以下规则:密码至少必须有一个大写和一个小写字符.密码至少有一个数字字符.至少有一个非字母数字字符写一个密码验证程序,用于检查一个字符串是否满足以上3条规则.你可能需要用到str的一下方法:isdigit(),isupper(),islower(),isalpha()2023/11/4FoundationsofMachineLearningLesson1-46Modules(模块)有多种方法可以编写模块,但最简单的方法是创建一个扩展名为.py的文件,其中包含函数和变量。模块可以由另一个程序导入以利用其功能。2023/11/4FoundationsofMachineLearningLesson1-47importsysprint('Thecommandlineargumentsare:')foriinsys.argv:

printi

print('\n\nThePYTHONPATHis',sys.path,'\n‘)字节编译的.pyc文件导入模块是一项相对昂贵的工作,因此Python会采取一些技巧使其更快。一种方法是创建扩展名为.pyc的字节编译文件,这是Python将程序转换为的中间形式(还记得介绍Python如何工作的部分吗?)。当您下次从其他程序导入模块时,这个.pyc文件非常有用,因为导入模块所需的一部分处理已经完成,所以它会更快。而且,这些字节编译的文件是独立于平台的。2023/11/4FoundationsofMachineLearningLesson1-48Thefrom…导入声明(from…import语句)如果要直接将argv变量导入程序(以避免键入sys)。然后可以使用fromsysimportargv语句。一般来说,您应该避免使用此语句而改用import语句,因为您的程序将避免名称冲突,并且更具可读性。例子:从数学导入sqrt打印(“16的平方根为”,sqrt(16))Example:frommathimportsqrtprint("Squarerootof16is",sqrt(16))2023/11/4FoundationsofMachineLearningLesson1-49Amodule’sname(模块的名)每个模块都有一个名称,模块中的语句可以找到其模块的名称。这对于确定模块是独立运行还是导入的特殊目的非常方便。Example:if__name__=='__main__':print('Thisprogramisbeingrunbyitself‘)else:print('Iambeingimportedfromanothermodule‘)2023/11/4FoundationsofMachineLearningLesson1-50MakingYourOwnModulesCreatingyourownmodulesiseasy.ThisisbecauseeveryPythonprogramisalsoamodule.Youjusthavetomakesureithasa.pyextension.Example(mymodule.py):2023/11/4FoundationsofMachineLearningLesson1-51def

say_hi():

print

'Hi,thisismymodulespeaking.'

__version__='0.1‘importmymodulemymodule.say_hi()Print('Version',mymodule.__version__)Thedirfunction(dir函数)可以使用内置的dir函数列出对象定义的标识符。例如,对于模块,标识符包括在该模块中定义的函数、类和变量。2023/11/4FoundationsofMachineLearningLesson1-52$python>>>importsys#getnamesofattributesinsysmodule>>>dir(sys)['__displayhook__','__doc__','argv','builtin_module_names','version','version_info']#onlyfewentriesshownhere当您向“dir()”函数提供模块名称时,它将返回在该模块中定义的名称列表。当没有参数应用于它时,它返回当前模块中定义的名称列表。2023/11/4FoundationsofMachineLearningLesson1-53#getnamesofattributesforcurrentmodule>>>dir()['__builtins__','__doc__','__name__','__package__']#createanewvariable'a'>>>a=5>>>dir()['__builtins__','__doc__','__name__','__package__','a']#delete/removeaname>>>dela>>>dir()['__builtins__','__doc__','__name__','__package__']Packages(包)Bynow,youmusthavestartedobservingthehierarchyoforganizingyourprograms.Variablesusuallygoinsidefunctions.Functionsandglobalvariablesusuallygomodules.Whatifyouwantedtoorganizemodules?That’swherepackagescomeintothepicture.Packagesarejustfoldersofmoduleswithaspecialinit.pyfilethatindicatestoPythonthatthisfolderisspecialbecauseitcontainsPythonmodules.2023/11/4FoundationsofMachineLearningLesson1-54-<somefolderpresentinthesys.path>/ -world/ -__init__.py -asia/ -__init__.py -india/ -__init__.py -foo.py -africa/ -__init__.py -madagascar/ -__init__.py -bar.pyDataStructures(数据结构)数据结构基本上就是——它们是可以将一些数据保存在一起的结构。换句话说,它们用于存储相关数据的集合。Python中有四种内置的数据结构:list、tuple、dictionary和set。我们将看到如何利用它们使我们的生活更容易。2023/11/4FoundationsofMachineLearningLesson1-55List(列表)list是处理一组有序项(item)的数据结构,即你可以在一个列表中存储一个

序列

(sequence)的项。假想你有一个购物列表,上面记载着你要买的东西,你就容易理解列表了。只不过在你的购物表上,可能每样东西都独自占有一行,而在Python中,你在每个项之间用逗号分割。列表中的项应该包括在方括号中,这样Python就知道你是在指明一个列表。一旦你创建了一个列表,你可以添加、删除或是搜索列表中的项。由于你可以增加或删除项,我们说列表是

可变的

(mutable)数据类型,即这种类型的数据在创建完后是可以被改变的。2023/11/4FoundationsofMachineLearningLesson1-56CreatingLists(创建列表)2023/11/4FoundationsofMachineLearningLesson1-57(1)Tocreatealist,putanumberofexpressionsinsquarebrackets:L=[]L=[expression,...]Thisconstructisknownasa“listdisplay”.(2)Computedlists,called“listcomprehensions:L=[expressionforvariableinsequence]wheretheexpressionisevaluatedonce,foreveryiteminthesequence.(3)使用内置列表类型对象创建列表:L=list()#emptylistL=list(sequence)L=list(expressionforvariableinsequence)AccessingLists

(访问列表元素)2023/11/4FoundationsofMachineLearningLesson1-58Lists实现标准的sequence接口;len(L)返回列表中的项数,L[i]返回索引i处的项(第一项的索引为0),L[i:j]返回一个新列表,包含i和j之间的对象。n=len(L)#列表的长度item=L[index]#列表中下标为index的项,下标从0开始seq=L[start:stop]#返回一个新的list,包括从start到stop的项如果传入负索引,Python会将列表的长度添加到索引中。L[-1]可用于访问列表中的最后一项。LoopingOverLists(依次访问list的元素)2023/11/4FoundationsofMachineLearningLesson1-59for-in语句使循环遍历列表中的项变得很容易:foriteminL:print(item)如果需要索引和项,请使用枚举函数:function:forindex,iteminenumerate(L):print(index,item)如果只需要索引,请使用range和len:forindexinrange(len(L)):print(index)ModifyingLists

(修改list中的元素)Thelisttypealsoallowsyoutoassigntoindividualitemsorslices,andtodeletethem.2023/11/4FoundationsofMachineLearningLesson1-60L[i]=objL[i:j]=sequenceL=[]M=L#modifybothlists

L.append(obj)L=[]M=L[:]#createacopy#modifyLonlyL.append(obj)ModifyingLists

(修改list中的元素)(续)2023/11/4FoundationsofMachineLearningLesson1-61L.append(item)L.extend(sequence)L.insert(index,item)delL[i]delL[i:j]item=L.pop()#lastitem

item=L.pop(0)#firstitem

item=L.pop(index)L.remove(item)L.reverse()L.sort()使用list例2023/11/4FoundationsofMachineLearningLesson1-62#!/usr/bin/python#Filename:using_list.py#Thisismyshoppinglistshoplist=['apple','mango','carrot','banana']print('Ihave',len(shoplist),'itemstopurchase.‘)print('Theseitemsare:‘)#Noticethecommaatendofthelineforiteminshoplist:print(item)2023/11/4FoundationsofMachineLearningLesson1-63print'\nIalsohavetobuyrice.'shoplist.append('rice')print('Myshoppinglistisnow',shoplist)print('Iwillsortmylistnow‘)shoplist.sort()print('Sortedshoppinglistis',shoplist)print('ThefirstitemIwillbuyis',shoplist[0])olditem=shoplist[0]delshoplist[0]print('Iboughtthe',olditem)print('Myshoppinglistisnow',shoplist)Tuple(元组)元组和列表十分类似,只不过元组和字符串一样是

不可变的

(immutable),即当你创建完一个元组后,你不能再修改元组。元组通过圆括号中用逗号分割的项目定义。元组通常用在使语句或用户定义的函数能够安全地采用一组值的时候,即被使用的元组的值不会改变。2023/11/4FoundationsofMachineLearningLesson1-64使用元组2023/11/4FoundationsofMachineLearningLesson1-65#!/usr/bin/python#Filename:using_tuple.pyzoo=('wolf','elephant','penguin')print('Numberofanimalsinthezoois',len(zoo))new_zoo=('monkey','dolphin',zoo)print('Numberofanimalsinthenewzoois',len(new_zoo))print('Allanimalsinnewzooare',new_zoo)print('Animalsbroughtfromoldzooare',new_zoo[2])print('Lastanimalbroughtfromoldzoois',new_zoo[2][2])含有0个或1个项目的元组一个空的元组由一对空的圆括号组成,如myempty=()。然而,含有单个元素的元组就不那么简单了。你必须在第一个(唯一一个)项目后跟一个逗号,这样Python才能区分元组和表达式中一个带圆括号的对象。即如果你想要的是一个包含项目2的元组的时候,你应该指明singleton=(2,)2023/11/4FoundationsofMachineLearningLesson1-66TuplesHaveNoMethods(元组没有方法)2023/11/4FoundationsofMachineLearningLesson1-67>>>t=('a','b','mpilgrim','z','example')>>>t.append("new")Traceback(innermostlast):File"<interactiveinput>",line1,in?AttributeError:'tuple'objecthasnoattribute'append'>>>t.remove("z")Traceback(innermostlast):File"<interactiveinput>",line1,in?AttributeError:'tuple'objecthasnoattribute'remove'>>>t.index("example")Traceback(innermostlast):File"<interactiveinput>",line1,in?AttributeError:'tuple'objecthasnoattribute'index'>>>"z"intTrue元组与打印语句元组最通常的用法是用在打印语句中,下面是一个例子:2023/11/4FoundationsofMachineLearningLesson1-68#!/usr/bin/python#Filename:print_tuple.pyage=22name='Swaroop'print('%sis%dyearsold'%(name,age))print('Whyis%splayingwiththatpython?'%name)Dictionary(字典)字典类似于你通过联系人名字查找地址和联系人详细情况的地址簿,即,我们把键(名字)和值(详细情况)联系在一起。注意,键必须是唯一的,就像如果有两个人恰巧同名的话,你无法找到正确的信息。注意,你只能使用不可变的对象(比如字符串)来作为字典的键,但是你可以不可变或可变的对象作为字典的值。基本说来就是,你应该只使用简单的对象作为键。键值对在字典中以这样的方式标记:d={key1:value1,key2:value2}。注意它们的键/值对用冒号分割,而各个对用逗号分割,所有这些都包括在花括号中。记住字典中的键/值对是没有顺序的。如果你想要一个特定的顺序,那么你应该在使用前自己对它们排序。2023/11/4FoundationsofMachineLearningLesson1-69DefiningDictionaries(定义字典)2023/11/4FoundationsofMachineLearningLesson1-70>>>d={"server":"mpilgrim","database":"master"}>>>d{'server':'mpilgrim','database':'master'}>>>d["server"]'mpilgrim‘>>>d["database"]'master‘>>>d["master"]Traceback(innermostlast):File"<interactiveinput>",line1,in?KeyError:masterModifyingDictionaries(修改字典)2023/11/4FoundationsofMachineLearningLesson1-71ExampleofModifyingaDictionary(修改字典例子)>>>d{'server':'mpilgrim','database':'master'}>>>d["database"]="pubs">>>d{'server':'mpilgrim','database':'pubs'}>>>d["uid"]="sa">>>d{'server':'mpilgrim','uid':'sa','database':'pubs'}2023/11/4FoundationsofMachineLearningLesson1-72Example:DictionaryKeysAreCase-Sensitive(字典的健是大小写敏感的)>>>d={}>>>d["key"]="value">>>d["key"]="othervalue">>>d{'key':'othervalue'}>>>d["Key"]="thirdvalue">>>d{'Key':'thirdvalue','key':'othervalue'}ExampleMixingDatatypesinaDictionary(字典中的健和值的数据类型都可以是不同的)2023/11/4FoundationsofMachineLearningLesson1-73>>>d{'server':'mpilgrim','uid':'sa','database':'pubs'}>>>d["retrycount"]=3>>>d{'server':'mpilgrim','uid':'sa','database':'master','retrycount':3}>>>d[42]="douglas">>>d{'server':'mpilgrim','uid':'sa','database':'master',42:'douglas','retrycount':3}DeletingItemsFromDictionaries(从字典中删除项)2023/11/4FoundationsofMachineLearningLesson1-74>>>d{'server':'mpilgrim','uid':'sa','database':'master',42:'douglas','retrycount':3}>>>deld[42]>>>d{'server':'mpilgrim','uid':'sa','database':'master','retrycount':3}>>>d.clear()>>>d{}使用字典2023/11/4FoundationsofMachineLearningLesson1-75#!/usr/bin/python#Filename:using_dict.py#'ab'isshortfor'a'ddress'b'ookab={'Swaroop':'swaroopch@','Larry':'larry@','Matsumoto':'matz@','Spammer':'spammer@'}print("Swaroop'saddressis%s"%ab['Swaroop'])2023/11/4FoundationsofMachineLearningLesson1-76#Addingakey/valuepairab['Guido']='guido@'#Deletingakey/valuepairdelab['Spammer']print'\nThereare%dcontactsintheaddress-book\n'%len(ab)forname,addressinab.items():print('Contact%sat%s'%(name,address))if'Guido'inab:#ORab.has_key('Guido')print("\nGuido'saddressis%s"%ab['Guido'])Sequence(系列)Lists,tuplesandstringsareexamplesofsequences,butwhataresequencesandwhatissospecialaboutthem?Themajorfeaturesaremembershiptests(成员测试),(i.e.theinandnotinexpressions)andindexingoperations(下标操作),whichallowustofetchaparticulariteminthesequencedirectly.Thethreetypesofsequencesmentionedabove-lists,tuplesandstrings,alsohaveaslicingoperation(取部分操作)whichallowsustoretrieveasliceofthesequencei.e.apartofthesequence.2023/11/4FoundationsofMachineLearningLesson1-772023/11/4FoundationsofMachineLearningLesson1-78shoplist=['apple','mango','carrot','banana']name='swaroop‘#Indexingor'Subscription'operation#print('Item0is',shoplist[0])print('Item1is',shoplist[1])print('Item2is',shoplist[2])print('Item3is',shoplist[3])print('Item-1is',shoplist[-1])print('Item-2is',shoplist[-2])print('Character0is',name[0])2023/11/4FoundationsofMachineLearningLesson1-79#Slicingonalist#print('Item1to3is',shoplist[1:3])print('Item2toendis',shoplist[2:])print('Item1to-1is',shoplist[1:-1])print('Itemstarttoendis',shoplist[:])#Slicingonastring#print('characters1to3is',name[1:3])print('characters2toendis',name[2:])print('characters1to-1is',name[1:-1])print('charactersstarttoendis',name[:])Set(集合)Setsareunorderedcollectionsofsimpleobjects.Theseareusedwhentheexistenceofanobjectinacollectionismoreimportantthantheorderorhowmanytimesitoccurs.Usingsets,youcantestformembership,whetheritisasubsetofanotherset,findtheintersectionbetweentwosets,andsoon.2023/11/4FoundationsofMachineLearningLesson1-802023/11/4FoundationsofMachineLearningLesson1-81>>>bri=set(['brazil','russia','india'])>>>'india'inbriTrue>>>'usa'inbriFalse>>>bric=bri.copy()>>>bric.add('china')>>>bric.issuperset(bri)True>>>bri.remove('russia')>>>bri&bric#ORersection(bric){'brazil','india'}References(引用)Whenyoucreateanobjectandassignittoavariable,thevariableonlyreferstotheobjectanddoesnotrepresenttheobjectitself!Thatis,thevariablenamepointstothatpartofyourcomputer’smemorywheretheobjectisstored.Thisiscalledbindingthenametotheobject.2023/11/4FoundationsofMachineLearningLesson1-822023/11/4FoundationsofMachineLearningLesson1-83print('SimpleAssignment‘)shoplist=['apple','mango','carrot','banana']#mylistisjustanothernamepointingtothesameobject!mylist=shoplist#Ipurchasedthefirstitem,soIremoveitfromthelistdelshoplist[0]print('shoplistis',shoplist)print('mylistis',mylist)#Noticethatbothshoplistandmylistbothprint#thesamelistwithoutthe'apple'confirmingthat#theypointtothesameobject2023/11/4FoundationsofMachineLearningLesson1-84print('Copybymakingafullslice‘)#Makeacopybydoingafullslicemylist=shoplist[:]#Removefirstitemdelmylist[0]print('shoplistis',shoplist)print('mylistis',mylist)#NoticethatnowthetwolistsaredifferentMoreAboutStrings(关于串字符)Wehavealreadydiscussedstringsindetailearlier.Whatmorecantherebetoknow?Well,didyouknowthatstringsarealsoobjectsandhavemethodswhichdoeverythingfromcheckingpartofastringtostrippingspaces!Thestringsthatyouuseinprogramareallobjectsoftheclassstr.Someusefulmethodsofthisclassaredemonstratedinthenextexample.Foracompletelistofsuchmethods,seehelp(str).2023/11/4FoundationsofMachineLearningLesson1-852023/11/4FoundationsofMachineLearningLesson1-86#Thisisastringobjectname='Swaroop'ifname.startswith('Swa'):print('Yes,thestringstartswith"Swa"')if'a'inname:print('Yes,itcontainsthestring"a"')ifname.find('war')!=-1:print('Yes,itcontainsthestring"war"')delimiter='_*_'mylist=['Brazil','Russia','India','China']print(delimiter.join(mylist))Python中的lambda、zip、map、reduce、filter函数2023/11/4Foundations

温馨提示

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

评论

0/150

提交评论