Comprehensions and Generations in Python

Source: Internet
Author: User
Tags for in range function definition generator iterable stdin

Both the comprehensions and the generations syntax in Python are used for iteration. The comprehensions syntax can be used on list,set,dictionary, while generations syntax is divided into generator functions and generator expressions.

Comprehensions

Take the list's comprehensions syntax as an example:

#General Syntax[Expression forTargetinchIterable] [x* * 2 forXinchRange (10)]#add an If statement[Expression forTargetinchIterableifCondiction] [x* * 2 forXinchRange (10)ifX% 2 = =0]#Full Syntax[Expression forTarget1inchInterable1ifCondition1 forTarget2inchInterable2ifCondition2 forTarget3inchInterable3ifCondition3 ... forTargetninchIterablenifCondictionn] [x+ y + Z forXinch 'spam' ifXinch 'SM'            forYinch 'SPAM' ifYinch('P','A')            forZinch '123' ifZ >'1']

With the full syntax of comprehensions, you can see that the comprehensions syntax is allowed to be nested, which equals nested for loops:

res = [] forXinch 'spam':    ifXinch 'SM':         forYinch 'SPAM':            ifYinch('P','A'):                 forZinch '123':                    ifZ >'1': Res.append[x+ y + z]

The comprehensions syntax for set and dictionary is similar to the comprehensions syntax for list, except that, for set, you only need to replace [] with {} In the list comprehensions syntax. For Dictinary, in addition to replacing [] with {},expression is delimited by: two expressions:

 for   in range (Ten)}          #  set syntax {0, 1, 4, Bayi, 9, +, +, + Range (Ten)}    #  dictionary syntax {0:0, 1:1, 2:4, 3:9, 4:16, 5:25, 6:36, 7:49, 8:64, 9:81}

Generations

Generations are divided into generator functions and generator expressions.

1 generator function

1) The definition of the generator function is the same as the normal function definition, except that the generator function needs to use the yield expression. The effect of the yield expression is to tell Python that an iterator is returned when the generator function is called. When traversing the returned iterator, the generator function starts running, and when it touches the yield expression, it returns the value of the yield expression to the iterator, and on the other hand pauses the execution of the generator function; The generator function continues to run the statement following the yiled expression so that it repeats itself until the iteration is complete:

defTest (): forIinchRange (5):        yieldIPrint('###')>>>g = Test ()#the call to the generator function returns an iterator>>>G<generator Object Test at 0x7f1246c1ee60>>>>next (G)#returns the value of the yield expression and pauses there0>>>next (G)#continue the iteration, run the statement after yield, and, because of the for loop, touch the yield statement again, return the value of the yield statement, and pause again###1>>>next (G)#Continue Iteration###2>>> Next (G)#Continue Iteration###3>>>>next (G)#Continue Iteration###4>>>next (G)#continue iteration, at which point the iteration ends## # # PRINT statement will still executeTraceback (most rencent): File"<stdin>", Line 1,inch<module>stopinteration

A return statement can also be included in the generator function, and if a return statement is encountered, the iteration will end prematurely:

defTest (): forIinchRange (5):        return        yield        Print('###')>>>g = Test ()#return iterator>>>G<generator Object Test at 0x7f1246c1eee08>>>>next (G)#iteration ends early when a return statement is encounteredTraceback (most recent): File"<stdin>", Line 1,inch<module>stopinteration

2) Send method

After Python 2.5, the iterator returned by the generator function can use the Send method. The Send method is also a traversal iterator, where the Send method allows a value to be passed, and this value becomes the return value of yield, in which case the yield is an expression instead of a statement:

 def   Test ():  for  I Range (5 = (yied i) + #   print< /span> ( '  %s%d   "% ("  ###   "  >>>g = Test ()  >>>next (G) #   You must first call the next method to start the iterator  0  >>> G.send (77 #  ##  1 

2-Generator expression

The generator expression is very similar to the list comprehensions, except that the [] will be replaced by (), and the parentheses are not required. If the generator expression is surrounded by parentheses, and the generator expression is the only expression inside the parentheses, you can omit the parentheses, otherwise you will need to use:

 for  in range (4))    #  brackets can omit  for in range (4)), reverse=true)    #  need to use parentheses

Scope

In Python 3.X, for variables of the comprehensions and generator expression's own life, the variable can only be used inside the comprehensions and generator expressions, and the variables cannot be accessed externally; in Python 2.X, Rules are basically the same as in Python 3.X, the only exception is in Python 2.X, list comprehensions life variables, not only the list comprehensions internal use, external can also access:

>>> (X forXinchRange (5))#python 3.X, python 2.X>>>Xnameerror:name'X'  is  notdefined>>>[x forXinchRange (5)]#Pyhon 3.X>>>Xnameerror:name'X'  is  notdefined>>>[x forXinchRange (5)]#Pyhon 2.X>>>x#can access4

Comprehensions and Generations in Python

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.