fromRange (3)Print(List (Gen2 ()))#[' A ', ' B ',------] list derivation and generator expressions:(Here is a small story to explain the knowledge points)#in order to show the essence of high-rich handsome, bought 10 tea egg, and they line up and numbered, photos sent to the circle of friendsegg_list=['Tea Egg%s'%i forIinchRange (10)]#List Parsing#but these 10 tea egg can not finish the breath, to eat is also a eat, then eat a picture of itEat=('Tea
The interview encountered a topic such as:Fibonacci Pocena sequence 1,2,3,5,8,13,21 .... According to this law, programming to find the maximum number of Fibonacci Pocena within 4 million, and to find out the number of the first few Fibonacci Pocena.Method One :method Two : This method uses the generator:Generator Description: With list generation, we can create a list directly. However, with memory limitations, the list capacity is certainly limited. And, creating a list of 1 million elements t
For calling a normal Python function, it is generally executed from the first line of the function, ending with a return statement, an exception, or all the statements of the function. Once the function returns control to the caller, it means that it is all over. All the work done in the function and the data saved in the local variables will be lost. When you call this function again, everything will be created from scratch.
Python learning Day 4 function slicing iterative list generator,
Define functions
Def my_abs (x): # evaluate the absolute value of the my_abs Function
If x> = 0:
Return x
Else:
Return-x
Def nop (): # Empty Function
Pass # placeholder
Parameter check
>>> My_abs (1, 2)
Traceback (most recent call last ):
File "
TypeError: my_abs () takes exactly 1 argument (2 given) # incorrect number of parameters
>>> My_
This article mainly introduces detailed information about the iterator and generator instances in Python. For more information, see the next article. it mainly introduces detailed information about the iterator and generator instances in Python, for more information, see
Details about the iterator and
In python, yield is such a generator.
Yield generator running mechanism:WhenWhen you ask the generator for a number, the generator will execute until the yield statement appears. The generator will give you the yield parameter,
iterator
An iterator is an object that implements the factory pattern, and it returns you every time you ask for the next value. For example, the Itertools function returns an iterator object.
4. Generator: Using the yield keyword, Python treats this function as a generator. It returns an iterative object that you can use next () to access it
印L1的意思 for i in L1:print (i) >>> g= Generator () #这里是一个生成器对象 >>> Next (g) #用next打印出来 [6, 7, 8, 9, ten] #生成器第2个例子 >>> def gen2 (): For I in L1:yield (i ) #打印i的值print (i) >>> g=gen2 () >>> print (g) 2, actually think is also quite simple, yield is just a logo, print the results at onceClassic case: Yang Hui Triangle#将杨辉三角的每一行看成一个list, write a generator (generator)
yield is meant to be generated, but in Python it is understood as a generator, and the usefulness of the generator can be iterated, simplifying many of the computational models (and not knowing how to simplify them). yield is an expression that has a return value.When a function contains yield, it is no longer a normal function, but rather a
777g = Funcl ()Print (g)Conclusion: # Analytical:First: As long as there is yield in the function, he is not a function, but a generator.Second: G is called the generator objectPerform:Print (g.__next__ ())Print (g.__next__ ())Print (g.__next__ ()) #超出yield数量, errorThe role of sentNext, like the Send function, is performed onceSend can assign a value to the previous yieldCases:Def generator ():Print (123)C
interrupted.Characteristics of the generator:
The corresponding data is generated only when it is called
Record the current location only
Only next, not prev.
Call of the generatorThere are two ways to call the generator to produce a new element:
Call the built-in next () method
Using loops to traverse a generator object (recom
I. List-derived1. The list derivation is a python-style notation. This is not only efficient, but also shorter. in [all]: [ ' i:el " for i,el in enumerate ([ " one " , two " , three " : [ i:el " , " i:el ", " i: El ] Enumerate is a built-in function that allows the list to have "subscript" properties.If you do not use a list deduction, the above example needs to be writtenIn []: LST = [" One"," Both","three"]in
saves memory 3.Python not only uses the iterator protocol, but also makes the for loop more generic. Most built-in functions also access objects using an iterator protocol. For example, the SUM function is a python built-in function that accesses an object using an iterator protocol, and the generator implements an iterator protocol, so we can calculate the sum
Yield is meant to be generated, but in Python it is understood as a generator, and the usefulness of the generator can be iterated, simplifying many of the computational models (and not knowing how to simplify them).
Yield is an expression that has a return value.
When a function contains yield, it is no longer a normal function, but rather a
The process under Python:1 #Encoding=utf-82 """3 the process----tiny processes4 Yield Generator-----Generate an iterative object such as list, Tuple,dir5 1, a function containing yield, it is an iterative object (list, tuple, etc.)6 end every run to yield and keep the scene7 2, producer, consumer behavior;8 9 3, do not need to execute immediately, only when neededTen """ One AA = [1, 2, 3, 4] - forIinchA:
List Builder# Common is the range () to create a list of numbers >>>[x*x for x in range (10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# back can also be added with a judgment statement >>>[ X*x for x in range (ten) if x%2 = = 0][0, 4, 16, 36, 64]# characters can also play this way >>> [M + N for m in ' ABC ' for n ' XYZ ' [' AX ', ' A Y ', ' AZ ', ' BX ', ' by ', ' BZ ', ' CX ', ' CY ', ' CZ '] Generator# Generator
How to create a generator:For x in range (1,10000000), Sir into a list [1........9999999] if we only want the next few elements, we will find a lot of wasted space. So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the
iterable type of the collections module:>>> from collections import Iterable>>> isinstance(‘abc‘, Iterable) # str是否可迭代True>>> isinstance([1,2,3], Iterable) # list是否可迭代True>>> isinstance(123, Iterable) # 整数是否可迭代FalseList-generatedThe list-generated type, which is comprehensions, is a very simple and powerful built-in Python build that can be used to create lists.1 #calculates the square of an even number in 1-102 3ll =range (1,11)4 5 Print[X*x forXinc
function is no longer a normal function, but a generator function.
But the generator function can produce a wireless sequence, so the list simply does not have a way to handle it.
the role of yield is to turn a function into a generator, a function with yield is no longer a normal function, and the Python i
The following small series for everyone to bring an example of the Python generator process operation. Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.
First, yield operation mode
We define a generator as follows:
def put_on (name): Print ("Hi {}, the goods are coming, rea
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.