After learning to finish the while loop, I'm finally going to fill in the pit for the For loop. This is because the for loop is valid for the previous sequence, dictionary, and collection, and the For loop is easier to get started with before you finish speaking the previous content.
First, the For loop, like the while loop, loops through the code of its inner layer when certain conditions are met. The difference is that the while loop determines the condition, and for determines the iteration object.
Let's look at the code for the For loop first:
A = (1, 2, 3, 4, 5) for in A: print x
Let's take the Ganso in the sequence as an example and find out that it outputs these, so what's the logic of this code? To make it easy for everyone to understand, I drew a diagram like this:
I wrote a small rent-collecting story to make it easy for everyone to understand. I don't know why I feel a little moist in my eyes when I write.
A For loop is a constant way to take elements from an iterative object, while an iterative object moves the pointer down one cell at a time of each iteration, that is, the next time you pick it up again. This is because an iterative object can behave like this, and it is called an iterative iteration.
This time I ask another question, does the value of x still exist after the iteration loop has ended?
And, of course, it says that the scope is something of a function, and iterative loops are not functions. According to the idea of the For loop, 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, X at the end of the loop, the value should be 5. That is x=5.
A = (1, 2, 3, 4, 5) for in A: print xprint' ---- ' , x Print A
In addition, although the rent is paid out of their own no, but the iterative cycle does not change a itself , that is, the equivalent of lending others to look at, things or their own.
Of course, there is no such welfare in reality.
The iterations of the sequence are the same as above, and are given sequentially in the order of the indexes. Dictionaries and collections are unordered, so the order in which the loops are obtained is different from the order in which we write the code. But I have said in the dictionary that the order of the dictionaries is embodied in their preservation, that is, once saved, the sequence is different from the order in which we write the code, but not every time we loop. If the order of each cycle is different then how much engineering, how much waste of computing resources, this obviously does not conform to the complexity of the Python simplification philosophy.
In addition, here is a reminder that the dictionary loop gets the key, and the collection does not have the concept of a key, so get the element.
1. Iterators and generators
You may see the following notation:
for in range (1,5): print x
Range () What the hell is our advanced switching mode look first:
Return a list directly, that is, this function is a quick production list, for loop is the equivalent of iterating over the list, it is good to understand.
There may also be a notation:
for in xrange (1,5): print x
Xrange () What the hell?
Returned to himself.
Well, here's an explanation of what the iterators and generators are.
1. iterators
An iterator is an object that implements an iterator protocol, and the iterator protocol in Python is that an object with the next method advances to the next result, and Stopiteration is thrown at the end of a series of results.
In the For Loop, ITER () is automatically called to convert the object we want to iterate into an iterative object, each time the loop is called . Next () method gets the new element and automatically exits the loop when the Stopiteration error is raised. This is the internal operation for the for loop.
Commonly used data types, such as: STR, tuple, list, dict, set, can iterate, because there are corresponding methods inside, such as list:
So we can also create an iterative class for ourselves:
classText ():def __init__(self,list_input):#initialization functionSelf.list =list_input self.i=0def __iter__(self):return SelfdefNext (self):ifSELF.I = = Len (self.list):#if the index is at the end, it means that the iteration is completeSELF.I = 0#return Index to 0 RaiseStopiteration#Trigger Error #if the index is not lastSELF.I + = 1#Index Shift One returnSELF.LIST[SELF.I-1]#Remove the value of the previous digit
A = Text ([x-ray]) for in A: print x
This is the iterator.
2. Generator
Xrange () is the generator.
The so-called generator is to save memory by returning an object each time it is called, rather than creating it in memory at once.
The generator is implemented by the yield keyword, and the generator is written like a function, except that the return of the function is changed to yield:
def SCQ (): yield 1 yield 2 yield 3= scq ()print a.next () Print a.next ()print a.next ()
Each time you call A.next (), you get a different value.
Of course we can also handle it like a function:
In short, the core of yield is the freezing function, once encountered, freezes the function, and return is the End function, once encountered, returns the result, the function exits, the next call to restart execution.
Of course, the last one will also trigger an error:
As you can see, the generator generates an object every time it is called, so the generator is more memory-efficient than an iterator, but it is also more CPU-intensive because the code needs to be operational. In general, however, the use of generators can be more efficient.
Finally, add the use of range and xrange two functions:
Both range and xrange accept three parameters:
Where start and stop represent the beginning and end of the same, not including the end of the value, the back is just a dividing line. When given only one parameter, the default starts at 0, which is start=0.
Step, which is the same as in the sequence, indicates that a few steps are taken to build once.
Write so much for the time being, what errors and additions will continue to improve.
Reference and reprint of the literature: poke here
15.python for loops and iterators, generators