15. python for loop and iterator, generator, 15. pythonfor

Source: Internet
Author: User

15. python for loop and iterator, generator, 15. pythonfor

After learning the while LOOP, We have to fill in the for loop. The reason for this delay is that the for loop is effective for the sequence, dictionary, and set mentioned above. It is easier to get started with the for loop after the previous content is explained.

First of all, the for loop is executed cyclically on its inner code when certain conditions are met, just like the while loop. The difference is that while loops determine conditions, while for judges iteration objects.

Let's first look at the for loop code:

a = (1, 2, 3, 4, 5)for x in a:    print x

 

Let's take the ancestor in the sequence as an example and find that it outputs this. What is the logic of this code? For your convenience, I drew a picture like this:

I wrote a small story about rent collection for your convenience.I don't know why I feel a little wet in my eye.

In fact, the for loop is constantly removing elements from the iteratable objects, and the iteratable objects will move the pointer down to one cell during each iteration, that is, the next time they come back, take the next one. This is because the iteratable object has such behavior and is called an iteration.

At this time, I have another question: After the iteration cycle ends, does the value of x still exist?

Of course, it is still said that the scope is a function, and the iteration loop is not a function. According to the for loop idea, the value of x is constantly updated, so at the end of the loop, x should be equal to the value of the last iteration. For example, the value of x at the end of the loop is 5. X = 5.

a = (1, 2, 3, 4, 5)for x in a:    print xprint '----',xprint a

 

  

In addition, although I have handed in my rentThe iteration loop does not change a itself.That is, it is equivalent to giving others a look, and things are still your own.

Of course, in reality, there is no such benefit.

  The iterations of the sequence are the same as those above, and are given in order of index. The dictionary and set are unordered, so the order obtained by the loop is different from the order written by our code. However, as I have mentioned in the dictionary, the disorder of the dictionary is reflected in its storage, that is, after it is saved, its order is different from the order in which our code is written, however, the order will not be different for each loop. If the order of each loop is different, how much project is required and how much computing resources are wasted is obviously not in line with the philosophy of simplifying python.

In addition, here is a reminder that the keys obtained by the dictionary loop, and the set does not have the concept of keys, so the obtained elements.

 

 

1. iterator and Generator

You may see the following statement:

for x in range(1,5):    print x

 

What is range ()? Let's take a look at the switch mode first:

  

A list is directly returned, that is, the function is a quick production list. The for loop is equivalent to an iterative list, which is easy to understand.

This statement may also be used:

for x in xrange(1,5):    print x

What is xrange?

Returned.

Okay, Let's explain what the iterator and generator are.

1. iterator

The iterator is an object that implements the iterator protocol. In Python, The iterator Protocol means that objects with the next method will move forward to the next result. At the end of a series of results, the StopIteration is triggered.

 

In the for loop, iter () is automatically called to convert the object to be iterated into an iterative object, which is called in each loop. the next () method gets the new element. When the StopIteration error is triggered, the loop is automatically exited, which is the internal operation of the for loop.

Common data types, such as str, tuple, list, dict, and set, can all be iterated, because they all have corresponding internal methods, such as in list:

Therefore, we can also create an iterative class:

Class Text (): def _ init _ (self, list_input): # initialization function self. list = list_input self. I = 0 def _ iter _ (self): return self def next (self): if self. I = len (self. list): # If the index reaches the end, the iteration is complete. I = 0 # Return the index to 0 raise StopIteration # Trigger Error # If the index does not reach the final self. I + = 1 # index shifts one return self. list [self. i-1] # retrieve the value of the previous Digit

 

a = Text([1,2,3])for x in a:    print x

This is the iterator.

 

2. Generator

Xrange () is the generator.

The so-called generator is to return an object each time it is called, instead of creating it in the memory at a time to save memory.

The generator is implemented by the yield keyword. The compilation of the generator is similar to a function, but the return of the function is changed to yield:

def scq():    yield 1    yield 2    yield 3a = scq()print a.next()print a.next()print a.next()

Each time a. next () is called, different values are obtained.

Of course, we can also process it like a function:

  In short, yield's core lies in freezing the function. Once it is encountered, it freezes the function. The return function ends the function. Once it is met, the result is returned, and the function exits. It will be executed again in the next call.

Of course, an error will also be triggered at the last time:

It can be seen that the generator generates an object each time it is called, so the generator saves more memory than the iterator, but also consumes more cpu because the code needs to be computed. However, it is generally more efficient to use a generator.

 

At last, the usage of the range and xrange functions is supplemented:

Range and xrange both accept three parameters:

  

Here, start and stop indicate start and end. They do not include the end value. The end value is just a dividing line. When only one parameter is provided, the default value starts from 0, that is, start = 0.

The step indicates the step size, which is the same as that in the sequence.

 

If you write so much for the time being, any errors and supplements will be improved.

Reference and reprinted documents: click here

 

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.