Examples of how to iterate and iterate in Python programming

Source: Internet
Author: User
Tags python list
Iteration
First understand what the iteration is, and all the ways in Python that sweep the polygon object from left to right are iterative

What are the possible ways to iterate:

1. File operation

When we read the file, we will use a ReadLine () method, in fact, it is an iterator, it will return the current data, and then automatically call the built-in next () method to let the file's reading head automatically move to the current line, prepare the next read, to reach the end of the file, An empty string is returned.

>>> f=open (' hello.py ') >>> f.readline () ' #!/usr/bin/python2.5\n ' >>> f.readline () ' print ' hello.word! " \ n ' >>> f.readline () ' \ n ' >>> f.readline () ' >>> for I in open (' hello.py '): ...       Print (i) ... #!/usr/bin/python2.5print "hello.word!"

Using the above way to read the contents of the file, the speed, memory consumption is also relatively low, especially for the operation of large files.

The following method is suitable for operating some small files, speed and efficiency is not good above, so it is recommended to operate the file later, try to use the above.

>>> for I in open (' hello.py '). ReadLines ():     ... Print I ... #!/usr/bin/python2.5print "hello.word!"

The Read method and the ReadLine method,
The read () method puts the contents of the entire file into a string
The ReadLine () method puts the contents of the file in the list according to the behavior unit.
In general to replace a character in the file, it is best to have a readline, and then loop through a line of content, and then find the replacement, so that efficiency than the entire read into a string to find the matching effect is higher.

2 for Loop

For example:

>>> for I in range (5): ...    

The process of processing it in the middle is the same as the following:

>>> l=[0,1,2,3,4]>>> i=iter (L) >>> i.next () 0>>> i.next () 1>>> I.next (2) >>> i.next () 3>>> i.next () 4>>> I.next ()

Traceback (most recent): File "
 
  
   
  ", line 1, in 
  
   
    
   stopiteration
  
   
 
  

Each call to the iterator invokes the next () method to return the result, and the file pointer moves down one line, and the end iteration of the exception has been stopiteration.


3. List Resolution:

A lot faster than a python for loop

For example:

>>> l=[x+10 for x in range (Ten)]>>> L

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Python iterates over range (10) in the interpreter, takes out the contents of the list, assigns it to the leftmost x, and then performs the x+10 operation.
And keep the results of the execution in the list. After the range (10) has been iterated, a new list is made, and the result is [10,11,12,13,14,15,16,17,18,19]
As can be seen from the above, this is also a way to build a python list.

The example above can also be implemented with a for loop.

>>> res=[]>>> for x in range: ...    Res.append (x+10) ... >>> res[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

As can be seen from the above, the Python list parsing is more streamlined than the manual for, and runs faster (often faster) because their iterations are executed at the speed of the C language inside the parser, rather than in manual Python code, especially for larger data sets, This is one of the main performance benefits of using list parsing.

Traverse
1. Iterating through the method of sequence fetching elements

#!/usr/bin/python2.5for i in ' hello ':  #序列里的字符串  print i, y = [1,2,3,4,5,6]  #列表for i in Y:  print I,

H e l l o 1 2 3 4 5 6

2. Traverse by the method of the sequence itself to offset the exponent (index)

That is, iterative sequence index, note: Iterate, repeat an instruction.

#!/usr/bin/python2.5x= ' Hello ' for I in range (len (x)):  print x[i] y = [1,2,3,4,5,6]for i in range (len (y)):  print y[ I],

H e l l o 1 2 3 4 5 6

The dictionary has 2 ways of fetching its value:

1. Take the dictionary key first, the value of the index

#!/usr/bin/python2.5z = {1: ' A ', 2: ' B ', 3: ' C '}for i in Z:  print z[i]

Abc

2. Through the dictionary items method, get all the key-value pairs, and the corresponding values are obtained by using the tuple splitting method.

#!/usr/bin/python2.5z = {1: ' A ', 2: ' B ', 3: ' C '}print z.items () for m,n in Z.items ():  

root@10.1.6.200:python# python 5.py

[(1, ' a '), (2, ' B '), (3, ' C ')]1 A2 b3 C
  • 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.