An example of how to iterate and traverse in Python Programming

Source: Internet
Author: User
Tags python list
This article mainly introduces how to iterate and traverse in Python programming. It is the basic knowledge of getting started with Python. For more information, see Iteration
First, understand what iteration is. In python, all methods of scanning objects from left to right are iteratable.

Which methods can be iterated:

1. File Operations

When reading a 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 automatically move the File Read header to the current row below, prepare for the next read, at the end of the file, will return an empty string.

>>> 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!"

If you use the above method to read the file content, the speed is very fast and the memory usage is relatively low, especially suitable for large files.

The following method is suitable for operations on some small files, and the speed and efficiency are not as good as above. Therefore, we recommend that you use the preceding method if you operate the files later.

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

Read and readline methods,
The read () method places the content of the entire file in the string.
The readline () method puts the file content in the list according to the behavior unit.
If you want to replace a character in a file, you 'd better have readline. Then, use a loop to loop the content of a row and search for replacement, this is more efficient than reading a string to search for matching results.

2 for Loop

For example:

>>> for i in range(5):...    print(i)... 

The intermediate processing process 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 call last): File "
 
  ", line 1, in 
  
   StopIteration
  
 

Each time the iterator is called, the next () method is called to return the result, move the file pointer down a row, and the iteration has ended due to a StopIteration exception.


3. List parsing:

Faster than python for Loop

For example:

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

[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Python iterates range (10) In the interpreter, extracts the content in the list in sequence, assigns the value to the leftmost x, and then executes the x + 10 operation,
And save the execution result in the list. After range (10) iteration, a new list is generated. The result is [,].
It can be seen from the above that this is also a method for creating a python list.

The preceding example can also be implemented using a for loop.

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

As can be seen from the above, python list Parsing is more streamlined than manual for, and runs faster (usually twice faster ), because their iterations are executed in the parser at the speed of C language rather than manual python code, especially for large data sets, this is a major performance advantage of list resolution.

Traversal
1. traverse through the element extraction method of the sequence

root@10.1.6.200:python# vim 3.py 

#! /Usr/bin/python2.5for I in 'hello': # print I, y = [1, 2, 3, 4, 5, 6] # list for I in y: print I,

root@10.1.6.200:python# python 3.py 

h e l l o 1 2 3 4 5 6

2. traverse through the sequence's own offset index (INDEX) Method

That is, the index of the iterative sequence. Note: iteration repeats a command.

root@10.1.6.200:python# vim 3.py 

#!/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],

root@10.1.6.200:python# python 3.py 

h e l l o 1 2 3 4 5 6

There are two ways to obtain the value of a dictionary:

1. Take the dictionary key first and obtain the index value.

root@10.1.6.200:python# vim 5.py 

#!/usr/bin/python2.5z = {1:'a',2:'b',3:'c'}for i in z:  print z[i]

root@10.1.6.200:python# python 5.py 

abc

2. Obtain all key-value pairs by using the items dictionary and obtain the corresponding values by using the tuples.

root@10.1.6.200:python# cat 5.py 

#!/usr/bin/python2.5z = {1:'a',2:'b',3:'c'}print z.items()for m,n in z.items():  print m,n 

root@10.1.6.200:python# python 5.py

[(1, 'a'), (2, 'b'), (3, 'c')]1 a2 b3 c

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.