Python Learning Note 3

Source: Internet
Author: User
Tags generator generator generator iterable set set

Merging strings

R to form the original string
+ Cannot directly connect a string and related values like C #.

Slice

It is possible to count from the beginning to the bottom. can also be separated by a certain distance to take

>>>Numlist=list (Range ( -))>>>numlist[0,1,2,3,4,5,6,7,8,9,Ten, One, A, -, -, the, -, -, -, +, -, +, A, at, -, -, -, -, -, in, -, to, +, -, the, *, $,Panax Notoginseng, -, the, +, A, the, +, -, $, $, -, -, the, -,Wuyi, the, -, Wu, -, About, $, -, -, -, A, +, the, -, $, the, the, the, the, -, in, the, the, About, the, the, the, +, -, the,Bayi, the, the, -, -, the, the, the, the, -, the, the, the,94, the, the, the,98, About]>>>numlist[:Ten) Syntaxerror:invalid Syntax>>>numlist[:Ten]#这里冒号前面的0能够省略[0,1,2,3,4,5,6,7,8,9]>>>numlist[:Ten:2][0,2,4,6,8]>>>numlist[-Ten::2]#这里冒号中间的-1 can be omitted;[ -, the,94, the,98]>>>numlist[-Ten::3][ -, the, the, About]>>>
Iteration:

An iterative object iterable, for ... in ..., enumerate function is able to put an index element pair, which is equivalent to a list of element pairs with ordinal and actual content
Containers and generators are iterative objects, and only generators are iterator objects.
The container contains a sequence (list and tuple), a set set, and a dictionary dict. Enumerate can generate index element pairs on a sequence.

mydict={}mydict[‘数学‘]=60mydict[‘语文‘]=90mydict[‘英语‘]=100forin mydict.items():    print(str,score)forin mydict.items():    print(str)forin enumerate(mydict.items()):print(index,str)
List-Generated

List generation is the process of simplifying the loop-generated list with a build.

Build-to-if statement union
forin range(1,11if x%2==0]print(generatedList);
Two for union can use a two-layer loop to form a full array
forin‘ABC‘forin [1,2,3]]print(allSortedList)
Lists all file and folder names under the current folder
importforin os.listdir(‘.‘)]print(dir)
The string becomes lowercase
#測试strlist=[‘Abc‘,‘dE12‘,334,‘12F‘]#strlist=[strs.lower() for strs in strlist if isinstance(strs,str)]forin strlist          ifnotor isinstance(strs.lower(),str)]print(strlist)
Generator

Assuming that the list elements can be extrapolated according to an algorithm, you do not have to generate a complete list. Just generate it on a need basis, so you can save memory space.

This is the generator generator (); generator is an algorithm, not a list, and the false assumption is that the next element needs to use next (g);

The generator is created in two ways. The first is the way to use the generated formula. Another way is to use the Definition builder function.


The build is also an Iterable object

Generating generators in a generative manner
forin range(1,10))forin g:    print(n)

The Iterable object, after iterating to the last element, assumes that continuing iterations produce stopiteration exceptions that can be captured.

#-_-! Coding:utf-8-_-!Mylist=list (Range (1, -)) forIndex,numinchEnumerate (myList): Print (Index,num)#迭代mydict={}mydict[' Math ']= -mydict[' Chinese ']= -mydict[' English ']= - forStr,scoreinchMydict.items (): Print (Str,score)#dict的默认是迭代key, can use the. Value () Iteration value to be able to use. Items () To iterate key-value pairs forStrinchMydict.items (): Print (str) forIndex,strinchEnumerate (Mydict.items ()): Print (INDEX,STR)#生成式#与if语句联合Generatedlist=[x*x forXinchRange1, One)ifX%2==0]print (generatedlist);#两个for联合#能够使用两层循环形成全排列allsortedlist=[(x, y) forXinch ' ABC '  forYinch[1,2,3]]print (Allsortedlist)#列出当前文件夹下全部文件和文件夹名ImportOsdir=[d forDinchOs.listdir ('. ')]print (dir)#字符串变小写#測试strlist=[' ABC ',' dE12 ',334,' 12F ']#strlist =[strs.lower () for STRs in Strlist if Isinstance (STRS,STR)]Strlist=[strs forSTRsinchStrlistif  notIsinstance (STRS,STR)orIsinstance (Strs.lower (), str)]print (strlist) lista=[1,2,3]listb=[2,3,4]lista=lista+listb;print (Lista)#生成器# #生成式的方式生成生成器G= (x*x forXinchRange1,Ten)) forNinchG:print (N)# #定义函数的方式生成生成器# # #斐波那契额数 1 1 2 3 5 8 def Fab(n):x,y,z=0,1,0     whileZ<n:yieldY#返回生成器的函数与其他函数的差别就在于print改成yied, you can call next () hereX,y=y,x+y#这里能够用作交换x, the value of Y is two lines less than other languagesz=z+1    return ' Done 'G=fab (Ten) forNinchG:print (N)# #捕获StopIteration异常 def Fab(n):x,y,z=0,1,0     whileZ<n:yieldY#返回生成器的函数与其他函数的差别就在于print改成yied, you can call next () hereX,y=y,x+y#这里能够用作交换x, the value of Y is two lines less than other languagesz=z+1    return ' Done 'F=fab (9) while True:Try: X=next (f) print (x)exceptStopiteration asE:print (' stopiteration is over. ', E.value) Break#杨辉三角 def triangles():x,y,z,temp=[1],0,0,[] while True:yieldX forNuminchX:temp.append (num+y) y=num temp.append (x[-1]+Z) x,temp,y=temp,[],0    return ' Done 'n=0 forTinchTriangles (): print (t) n=n+1    ifn==Ten: Break

Python Learning Note 3

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.