Learning Python with the old is a joy and a worry iteration

  • 2020-04-02 14:12:03
  • OfStack

Oh, this is a really cool programmer. However, he is only a cow, not a god. What is a great programmer? He is a sweeping monk, big in the city.

Make sure you understand these terms before you go on:

The loop, This refers to the repeated execution of the same piece of code if the condition is met. For example, a while statement.
Iterate, This refers to accessing each item in a list in some order. For example, the for statement.
Recursion, The act of a function calling itself over and over again. For example, programmatically output the famous Fibonacci sequence.
Traversal, traversal, Refers to accessing each node in the tree structure according to certain rules, and each node is accessed only once.
As for these four enigmatic words, we have covered one -- loop -- in the tutorial. This tutorial is mainly about iteration, and you will find many articles comparing iteration with loop and recursion on Google, and comparing them from different angles. I'm not going to do any comparisons here, but let's just make sense of iterations in python. I'll compare them later, if I don't forget, haha.

One by one to visit

In python, you can access each element in an object by doing this :(for example, a list)


>>> lst
['q', 'i', 'w', 's', 'i', 'r']
>>> for i in lst:
...     print i,
...
q i w s i r

In addition to this method, you can also:


>>> lst_iter = iter(lst)    # To the original list Implemented a iter()
>>> lst_iter.next()         # Take the trouble to manually access one by one
'q'
>>> lst_iter.next()
'i'
>>> lst_iter.next()
'w'
>>> lst_iter.next()
's'
>>> lst_iter.next()
'i'
>>> lst_iter.next()
'r'
>>> lst_iter.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

As a good programmer, the best quality is "lazy", of course, can not be such a knock, so:


>>> while True:
...     print lst_iter.next()
...
Traceback (most recent call last):      # Report an error, and the error is the same as before? What's the cause of the
  File "<stdin>", line 2, in <module>
StopIteration >>> lst_iter = iter(lst)                # Then write again, the above mistakes aside, back to study
>>> while True:
...     print lst_iter.next()
...
q                                       # Sure enough, it was read automatically
i
w
s
i
r
Traceback (most recent call last):      # After reading the last one, report an error and stop the loop
  File "<stdin>", line 2, in <module>
StopIteration
>>>

Let's start with the built-in function iter(), described in the official document as:


iter(o[, sentinel])
Return an iterator object. The first argument is interpreted very differently depending on the presence of the second argument. Without a second argument, o must be a collection object which supports the iteration protocol (the iter() method), or it must support the sequence protocol (the getitem() method with integer arguments starting at 0). If it does not support either of those protocols, TypeError is raised. If the second argument, sentinel, is given, then o must be a callable object. The iterator created in this case will call o with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

To the effect that... (here deliberately omitted several words, because I believe that the reading of this article is the level of English reading documents, no cleavage, also don't worry, find a dictionary or something to help.)

Although I won't translate it, I still need to refine the main things:

The return value is an iterator object
The parameter needs to be either an object that conforms to the iteration protocol or a sequence object
Next () works with it
What is an "iterable object"? In general, we often refer to objects that can read elements one by one using a for as iterable objects. So for is also called an iteration tool. The so-called iteration tool is able to scan every element of the iteration object in a certain order (from left to right). Obviously, there are other iteration tools besides for, such as list parsing and in to determine whether an element belongs to the sequence object.

Now, what about iter()? It is also used in conjunction with next() to implement the iteration tool described above. In python, and even in other languages, the iteration part is a little bit messy, mainly in terms of the noun, but as we said, the things that can do iteration are called iteration tools, and that's what iteration tools are, and a lot of programmers like to call them iterators. Of course, this is all a Chinese translation, English is iterator.

If you look at all the examples above, you will see that if you use for to iterate, when you reach the end, it will automatically end without any errors. If use the iter ()... Next () iteration. When the last iteration is finished, it doesn't automatically end, it continues down, but there are no more elements, so it reports an error called StopIteration.

Iter ()... A feature of the next() iteration. When the iteration object lst_iter is iterated over, that is, after each element is read on one side, the pointer moves behind the last element. If it is accessed again, the pointer does not automatically return to the first position, but still stays at the last position, so it is checked with StopIteration to start again, so it needs to reenter the iteration object. So, the column bits see that when I iterate over the object assignment above, I can continue. This is not available in iteration tools such as for.

File iterator

Now there is a file, name: 208.txt, which is as follows:


Learn python with qiwsir.
There is free python course.
The website is:
http://qiwsir.github.io
Its language is Chinese.

Iterator to operate this file, we have done in the previous about the file knowledge, nothing more than:


>>> f = open("208.txt")
>>> f.readline()        # Read the first line
'Learn python with qiwsir.n'
>>> f.readline()        # Read the second line
'There is free python course.n'
>>> f.readline()        # Read the third line
'The website is:n'
>>> f.readline()        # Read the fourth row
'http://qiwsir.github.ion'
>>> f.readline()        # Read the fifth line, which is really after the last line, to the end of the line
'Its language is Chinese.n'
>>> f.readline()        # No more content, but no error, return empty.
''

The above example demonstrates reading line by line with readline(). Of course, in practice, we can never do this, we must make it automatic, the more common method is:


>>> for line in f:     # This operation is followed by the operation above, please watch the main observation
...     print line,    # Nothing was printed out
...

This code doesn't print anything because the pointer has moved to the end after the previous iteration. That's one of the things about iteration, you have to be careful where the pointer is.


>>> f = open("208.txt")     # Start all over again
>>> for line in f:
...     print line,
...
Learn python with qiwsir.
There is free python course.
The website is:
http://qiwsir.github.io
Its language is Chinese.

This method is commonly used to read files. Another readlines() also works. However, there are some things to be careful of. If you can't remember what to be careful of, you can review the course on documents.

The above procedure can also be read using next().


>>> f = open("208.txt")
>>> f.next()
'Learn python with qiwsir.n'
>>> f.next()
'There is free python course.n'
>>> f.next()
'The website is:n'
>>> f.next()
'http://qiwsir.github.ion'
>>> f.next()
'Its language is Chinese.n'
>>> f.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

If you use next(), you can read each line directly. This means that the file is naturally iterable and does not need to be converted with iter().

Again, we use "for" to iterate, in essence, automatically calling next (), only this work, has let "for" secretly do it for us, here, column should give "for" another name: it is called lei feng.

As mentioned earlier, list parsing can also be used as an iteration tool, which should be clear to the reader when studying a list. So for the file, can I use it? Give it a try:


>>> [ line for line in open('208.txt') ]
['Learn python with qiwsir.n', 'There is free python course.n', 'The website is:n', 'http://qiwsir.github.ion', 'Its language is Chinese.n']

At this point, isn't the viewer impressed by the list resolution? It's really strong, strong and big.

In fact, iterators are much more than that. Let's just list a few of them, and in python you can also get elements in an iterated object in this way.


>>> list(open('208.txt'))
['Learn python with qiwsir.n', 'There is free python course.n', 'The website is:n', 'http://qiwsir.github.ion', 'Its language is Chinese.n'] >>> tuple(open('208.txt'))
('Learn python with qiwsir.n', 'There is free python course.n', 'The website is:n', 'http://qiwsir.github.ion', 'Its language is Chinese.n') >>> "$$$".join(open('208.txt'))
'Learn python with qiwsir.n$$$There is free python course.n$$$The website is:n$$$http://qiwsir.github.ion$$$Its language is Chinese.n' >>> a,b,c,d,e = open("208.txt")
>>> a
'Learn python with qiwsir.n'
>>> b
'There is free python course.n'
>>> c
'The website is:n'
>>> d
'http://qiwsir.github.ion'
>>> e
'Its language is Chinese.n'

The above approach is not necessarily useful in programming practice, but just to show the viewer that it can be done, not necessarily done.

Add, the dictionary can also be iterated, read their own might as well fumble (in fact, the previous for iteration has been used, this time please fumble with iter()... Next () manually iterate step by step.


Related articles: