One. Parallel iterations.
If the parallel iteration, the first push zip () Function!!!
For example, there are now two of the same length of the list, the two lists, the index position of the same value is associated, now you have to traverse the values of both tables, if you encounter this situation, you must use a parallel iteration.
name = ["Suhaozhi", "Andy", "Tony"]
Age = [22,33,44]
If the name table is the name of each person, the age table is the ages of these three people, all by location, and now it is necessary to loop the iteration, these two lists.
name = ["Suhaozhi", "Andy", "Tony"]
Age = [22,33,44]
For I in range (len (name)):
Print "name:%s age:%s"% (Name[i],age[i])
The output results are as follows:
Name:suhaozhi age:22
Name:andy age:33
Name:tony age:44
This actually implements the two-list iteration loop at the same time, but there is an easier way to do this, which is the zip function.
name = ["Suhaozhi", "Andy", "Tony"]
Age = [22,33,44]
For n,a in Zip (name,age):
Print "name:%s age:%s"% (n,a)
Attention!! There are two points to add to the ZIP function:
The zip function can "compress" n multiple sequences at the same time.
The ZIP function can also handle sequences of unequal lengths, when two or more unequal sequences are processed together, whichever is the shortest sequence, as long as the shortest sequence runs out, it stops.
Here is an example:
L1 = [' One ', ' both ', ' three ']
L2 = [1,2,3,4,5,6]
Print zip (L1,L2)
The output results are as follows:
[(' One ', 1), (' One ', 2), (' Three ', 3)]
The shortest sequence is used up, it is not processed in the future.
Two. Iterate by index.
You can use the enumerate function when you want to iterate over an object in a sequence and want to get the index of the current object.
L1 = [' A ', ' B ', ' C ', ' d ', ' e ']
For I in Enumerate (L1):
Print I
The output results are as follows:
(0, ' a ')
(1, ' B ')
(2, ' C ')
(3, ' d ')
(4, ' e ')
This article is from the "Rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1906505
The iterative method in 2.python for the basis of sequence comparison.