Learn Python with the old and interesting iterations, and learn python

Source: Internet
Author: User

Learn Python with the old and interesting iterations, and learn python

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)

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

Copy codeThe 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 "<stdin>", line 1, in <module>
StopIteration

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

Copy codeThe 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 "<stdin>", line 2, in <module>
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 "<stdin>", line 2, in <module>
StopIteration
>>>

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

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

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

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

Copy codeThe 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.

Copy codeThe 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.

Copy codeThe 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 "<stdin>", line 1, in <module>
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:

Copy codeThe 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.

Copy codeThe 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 ).


What does iteration in python mean?

The above definition of mathematics: iteration formula refers to the use of the current value, instead of a formula, to calculate the next value, and then the next value into the formula, so reciprocating generation. For example, if x = (x + 2/x)/2, you can substitute x = 10 for x = (10 + 2/10)/2 = 5.1, x = (5.1 + 2/5.1)/2 = 2.746, and then 1.737, and so on.
In python, iterations can also be recursive calls. The following is an example:
Def f (n ):
If n = 0 or n = 1 or n = 2: return 1
Else: return f (n-1) + f (n-2)
This is a simple method for finding the nth Fibonacci number. Here we use an iteration. In addition, the Newton iteration method is used to obtain the number of operators of n based on the progressive effect. The following is an example:
Def f (guess ):
Return guess ** 2
Def fd (guess ):
Return 2 * guess
Def SquareRootNR (x, epsilon ):
Guess = x/2.0
Diff = f (guess)-x
Ctr = 1
While abs (diff)> epsilon and ctr <= 100:
Guess = guess-diff/fd (guess)
Diff = f (guess)-x
Ctr + = 1
Return guess

If you have any questions, please ask. If you are satisfied, please accept them!

A simple iteration problem for python

Def power (x, y): "" bunengshixiaoshu "if (isinstance (x, int) or (isinstance (x, float ))) and (isinstance (y, int) or (isinstance (y, float): if (x! = 0) and (y> = 0): if (y = 0): return 1 elif (y = 1): return x else: return x * power (x, y-1) else: print "Wrong range" x = input ('Please input the value of x again: ') y = input ('Please input the value of y again :') print x print y return power (x, y) else: print "The parameters must be numbers. "x = input ('Please input the value of x: ') y = input ('Please input the value of y:') print power (x, y) power (x, y)
Print power (x, y)
The last two rows actually execute the power (x, y) function twice. The previous operation is performed once, and the print operation is performed again later, the second "Wrong range" error message is actually given again. The first execution of the local variable x and y entered in the print power function has ended.
In the negative input judgment of the power Function y, the final power (x, y) of the else block should be return power (x, y). Otherwise, no return value will be returned after another input, therefore, print power (x, y) will print None


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.