Learning Python with old people is an exciting and worrying iteration

Source: Internet
Author: User
I often hear an unstandard English word coming out of my mouth when talking to some cool X programmers. if loop, iterate, traversal, and recursion are not there, I always think they are not good enough. Let's say that the real ox X will never say that. they just say "loop, iteration, traversal, recursion" and then ask "Do you understand this ?". Oh, this is a real cool x programmer. However, he is just a cow X, not a great God. What are great programmers like? He swept the floor, hiding in the city.

First, let's clarify these terms and talk about other terms:

Loop ),It refers to repeated execution of the same piece of code when the conditions are met. For example, the while statement.
Iteration (iterate ),Each item in the list is accessed one by one in a certain order. For example, the for statement.
Recursion (recursion ),It refers to a function that constantly calls itself. For example, output the famous Fibonacci series programmatically.
Traverse (traversal ),It refers to accessing each node in the tree structure according to certain rules, and each node is only accessed once.
The four uncertain words have already involved a loop in the tutorial. in this article, I will mainly introduce the iteration (iterate, we will find that there are many articles on comparison between iterations, loops, and recursion, and they are compared from different angles. This is not a comparison for the time being. First, understand the iterations in python. Then compare them at an appropriate time. if I don't forget it, haha.

Access one by one

In python, you can access every element of an object by doing the following: (for example, a list)

The code is as follows:


>>> 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:

The code is as follows:


>>> Lst_iter = iter (lst) # implements an iter () for the original list ()
>>> Lst_iter.next () # manually access
'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" ", Line 1, in
StopIteration

As a good programmer, the best quality is "laziness". of course, you can't think about it one by one:

The code is as follows:


>>> While True:
... Print lst_iter.next ()
...
Traceback (most recent call last): # An error is reported, and the error is the same as the previous one? Why?
File" ", Line 2, in
StopIteration

>>> Lst_iter = iter (lst) # write it again. The above error is put on hold for the moment.
>>> While True:
... Print lst_iter.next ()
...
Q # I read it automatically
I
W
S
I
R
Traceback (most recent call last): # After reading the last one, an error is reported and the loop is stopped.
File" ", Line 2, in
StopIteration
>>>

First, let's take a look at the built-in function used above: iter (), which is described in the official document as follows:

The code is as follows:


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.

It means... (Here, I intentionally omit a few words, because I believe that the reading level of the official English in this article has reached the level of reading the document. if there is no cleavage, you don't have to worry about it. please find a dictionary or something to help .)

Although it is not translated, we need to extract the main things:

The returned value is an iterator object.
The parameter must be an iteration protocol object or a sequence object.
Use with next ()
What is "iteratable object? In general, we often refer to the objects that can use for to read Elements one by one as iteratable objects. Therefore, for is called an iteration tool. The so-called iteration tool is to scan every element of the iteration object in a certain order (from left to right). Obviously, in addition to for, there are other tools that can be called iteration tools, for example, list parsing and in to determine whether an element belongs to a sequence object.

So what about the iter () function just introduced? It works with next () and is also used to implement the above iteration tool. In python, and even in other languages, the concept of iteration is messy, mainly due to the disorder of terms. just now we said that those things that can implement iteration are called iteration tools, many programmers like these iteration tools. Of course, these are all Chinese translations, and English is iterator.

When you look at all the examples above, you will find that if you use for iteration, it will automatically end at the end of the iteration and no error will be reported. If iter ()... next () iteration. after the last iteration is completed, it will not automatically end, but it will continue downward, but there will be no elements in the future, therefore, an error called StopIteration is reported (this error is called "Stop iteration", which clearly indicates an error ).

The reader also pays attention to a feature of iter ()... next () iteration. When the iteration object lst_iter ends, that is, after each element reads one side, the pointer moves to the end of the last element. If you access the object again, the pointer does not automatically return to the first position, but remains at the last position. Therefore, StopIteration is reported. to start again, you need to re-repeat the iteration object. So, the column bit will show that when I re-increment the row iteration object above and assign a value, I can continue again. This is not available in for and other types of iteration tools.

File iterator

Now there is a file named 208.txtwhose content is as follows:

The code is as follows:


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

When we use the iterator to operate this file, we have done it before we talk about the file-related knowledge, nothing more:

The code is as follows:


>>> F = open ("208.txt ")
>>> F. readline () # read the first row
'Learn python with qiwsir. \ n'
>>> F. readline () # read the second row
'There is free python course. \ n'
>>> F. readline () # read the third row
'The website is: \ n'
>>> F. readline () # read the fourth row
'Http: // qiwsir. github. io \ n'
>>> F. readline () # read the fifth line, that is, after reading the last line
Its language is Chinese. \ n'
>>> F. readline () # no content, but no error is reported. the returned value is null.
''

The preceding example uses readline () to read data in one row. Of course, in practice, we absolutely cannot do this. we must make it automatically. the more common method is:

The code is as follows:


>>> For line in f: # this operation is followed by the above Operation. please refer to the official observation.
... Print line, # nothing printed
...

This code does not print out anything because the pointer has been moved to the end after the previous iteration. This is a feature of iteration. be careful with the pointer position.

The code is as follows:


>>> F = open ("208.txt") # start from scratch
>>> 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 () can also be used. However, you need to be careful. if you cannot think of anything, you can review the course about the document.

The above process can also be read using next.

The code is as follows:


>>> 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. io \ n'
>>> F. next ()
Its language is Chinese. \ n'
>>> F. next ()
Traceback (most recent call last ):
File" ", Line 1, in
StopIteration

If you use next (), you can directly read the content of each row. This indicates that the file is a natural iteratable object and does not need to be converted by iter.

In addition, we use for to implement iteration. in essence, we call next () automatically, but this job has already made for US secretly. here, should the column for be given another name: Lei Feng.

As mentioned above, list parsing can also be used as an iteration tool. when studying the list, you must be clear about it. Can the file be used? Try:

The code is as follows:


>>> [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. io \ n', 'Its language is Chinese. \ n']

At this point, isn't the official account considered as a list resolution service? It's really powerful, strong, and big.

In fact, the iterator is far more simple than the above. let's list some of them at will. in python, we can also get the elements in the iteration object.

The code is as follows:


>>> List(open('208.txt '))
['Learn python with qiwsir. \ n', 'There is free python course. \ n', 'The website is: \ n', 'http: // qiwsir. github. io \ n', '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. io \ n', '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.io \ n $ Its language is Chinese. \ n'

>>> A, B, c, d, e = open ("208.txt ")
>>>
'Learn python with qiwsir. \ n'
>>> B
'There is free python course. \ n'
>>> C
'The website is: \ n'
>>> D
'Http: // qiwsir. github. io \ n'
>>> E
Its language is Chinese. \ n'

The above method is not necessarily useful in programming practice. it just shows it to the viewer, and the viewer must understand that it can do this, not necessarily.

The dictionary can also be iterated. you may wish to explore it yourself (in fact, we have already used for iteration. please try again this time using iter ()... next () manual step by step iteration ).

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.