With the old Ziko Python's happy and worrying iteration _python

Source: Internet
Author: User
Tags readline stdin in python

Oh, this is the real Cow x programmer. However, he is only a cow x, not a great God. What's the big God programmer like? He is a sweeping monk, a big faint in the city.

Let's find out what these nouns say:

Loop, which refers to repeating the same piece of code when conditions are met. For example, the while statement.
iteration (iterate), which refers to accessing each item in a list in a certain order, individually. For example, for statement.
recursion (recursion) refers to a function that constantly invokes its own behavior. For example, a well-known Fibonacci sequence is exported programmatically.
Traversal (traversal) refers to the access to each node in the tree structure in accordance with certain rules, and each node is accessed only once.
For these four sounding words, in the tutorial, has been involved in a-loop (loop), the main introduction of the iteration (iterate), reader Google on the Internet, you will find that for iterations and loops, recursive comparisons between the article a lot of They are compared from different angles respectively. Here is a short comparison, first understand the iteration in Python. Then the appropriate time to compare, if I do not forget, haha.

Individual access

In Python, you can access each element of an object by doing so: (for example, a list)

Copy Code code 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 do this:

Copy Code code as follows:

>>> lst_iter = iter (LST) #对原来的list实施了一个iter ()
>>> Lst_iter.next () #要不厌其烦地一个一个手动访问
' 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, and then:

Copy Code code as follows:

>>> while True:
... print lst_iter.next ()
...
Traceback (most recent call last): #居然报错, and the error is the same as the front face? What's the reason?
File "<stdin>", line 2, in <module>
Stopiteration

>>> lst_iter = iter (LST) #那就再写一遍, the above error aside, back in the study
>>> while True:
... print lst_iter.next ()
...
Q #果然自动化地读取了
I
W
S
I
R
Traceback (most recent call last): #读取到最后一个之后, error, stop loop
File "<stdin>", line 2, in <module>
Stopiteration
>>>

First, take a look at the built-in function used above: ITER (), which is described in the official document:

Copy Code code as follows:

ITER (o[, Sentinel])
Return an iterator object. The argument is interpreted very differently depending on the presence of the second. 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 an integer arguments starting at 0). If it does not support either of the those protocols, TypeError is raised. If The second argument, Sentinel, is given, then o must to be a callable object. The iterator created in this case would call O and no arguments for each call to its next () method; If the value returned is equal to Sentinel, Stopiteration'll be raised, otherwise the value would be returned.

To the effect that ... (intentionally omitted a number of words here, because I believe that reading this article reader English level is to see the level of the document, the cleavage does not, also need not worry, find a dictionary what help. )

Although not translated, but also to refine the main things:

The return value is an iterator object
The parameter needs to be an object that conforms to the iteration protocol or is a sequence object
Next () with the use of
What is an "iteration object"? In general, we often refer to what can be used as an object to read an element, called an iterative object. Then the for is also called an iterative tool. An iterative tool is the ability to scan each element of an iterative object in a certain order (in Left-to-right order), and obviously there is something else to be called an iterative tool, such as list parsing, in to determine whether an element belongs to a sequence object, and so on.

So, what's the function of ITER () just introduced? It is used in conjunction with Next () and is also useful for implementing the above iterative tools. In Python, even in other languages, iterations of this piece of the argument is more chaotic, mainly noun disorder, just now we said that those who can implement the iteration, called the iterative tool, is these iterative tools, many programmers like to call iterators. Of course, this is all Chinese translation, English is iterator.

Reader look at all the examples above will find that if you use for to iterate, when the end of the time, it automatically ended, no error. If you use ITER () ... next () iteration, when the last one is completed, it will not automatically end, but also go down, but there is no element behind, so the report called a stopiteration error (the wrong name is called: Stop the iteration, where is the error, clear warning).

Reader also pay attention to a feature of ITER (). Next () iteration. The pointer moves to the back of the last element when the iteration object Lst_iter is finished by the iteration, after each element is read one side. If you access again, the pointer does not automatically return to the first position, but still stay in the last position, so the newspaper stopiteration, want to start again, you need to re-enter the iteration object. So, as you can see, when I iterate over the object assignment above, it's OK to continue. This is not in a for-type iteration tool.

File iterators

Now there is a file, name: 208.txt, whose contents are as follows:

Copy Code code as follows:

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

Using iterators to manipulate this file, we've done it before about the knowledge of the file:

Copy Code code as follows:

>>> f = open ("208.txt")
>>> F.readline () #读第一行
' Learn python with qiwsir.\n '
>>> F.readline () #读第二行
' There are free python course.\n '
>>> F.readline () #读第三行
' The website is:\n '
>>> F.readline () #读第四行
' Http://qiwsir.github.io\n '
>>> f.readline () #读第五行, which is really after reading the last line, to the end of this trip
' Its language is chinese.\n '
>>> f.readline () #无内容了, but no error, return empty.
''

The above demo is to read with ReadLine () line by row. Of course, in the actual operation, we absolutely can not do so, we must let it automatically, more commonly used methods are:

Copy Code code as follows:

>>> for line in F: #这个操作是紧接着上面的操作进行的, please reader main observation
... print line, #没有打印出任何东西
...

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

Copy Code code as follows:

>>> f = open ("208.txt") #从头再来
>>> 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 often used to read files. Another readlines () can also be. However, there is a need for some care, reader if you can't remember what to be careful, you can review the document on the side of the course.

The above procedure can also be read with Next ().

Copy Code code as follows:

>>> f = open ("208.txt")
>>> F.next ()
' Learn python with qiwsir.\n '
>>> F.next ()
' There are 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 "<stdin>", line 1, in <module>
Stopiteration

If you use Next (), you can read the contents of each row directly. This indicates that the file is a natural and iterative object and does not need to be converted with ITER ().

Again, we use for to implement the iteration, in essence, is automatically called Next (), but this work, has been for secretly for us to do, here, you should give for a different name: it is called Lei Feng.

As mentioned earlier, list parsing can also be an iterative tool, and reader must have been clear in the study list. So is the file, can you use it? Give it a try:

Copy Code code as follows:

>>> [line for line in open (' 208.txt ')]
[' Learn python with qiwsir.\n ', ' There are free python course.\n ', ' website is:\n ', ' http://qiwsir.github.io\n ', ' its L Anguage is chinese.\n ']

So far, reader not for the list of resolution to be impressed? Really strong, strong and big AH.

In fact, the iterator is much more than that, so let's just enumerate some of the elements in the iteration object in Python.

Copy Code code as follows:

>>> List (open (' 208.txt '))
[' Learn python with qiwsir.\n ', ' There are free python course.\n ', ' website is:\n ', ' http://qiwsir.github.io\n ', ' its L Anguage is chinese.\n ']

>>> Tuple (open (' 208.txt '))
(' Learn python with qiwsir.\n ', ' There are free python course.\n ', ' website is:\n ', ' http://qiwsir.github.io\n ', ' its L Anguage is chinese.\n ')

>>> "$$$". Join (Open (' 208.txt '))
' Learn python with qiwsir.\n$$ $There are 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")
>>> A
' Learn python with qiwsir.\n '
>>> b
' There are free python course.\n '
>>> C
' The website is:\n '
>>> D
' Http://qiwsir.github.io\n '
>>> E
' Its language is chinese.\n '

The above way, in the programming practice is not necessarily used, just to reader show, and reader to understand, can do so, not have to do so.

To add, the dictionary can also be iterated, reader oneself may wish to grope (in fact, already used for iterative past, this time, please find out with ITER () ... next () manually iteration by step).

Related Article

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.