Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!
In the "Loops" section, we have discussed Python's basic looping syntax. In this section, we will be exposed to a more flexible loop approach.
Range ()
In Python, the For loop after in follows a sequence, looping through each use of the sequence element instead of the subscript of the sequence.
We have previously used range () to control the For loop. Now, we continue to develop the function of range to achieve the control of the loop on the subscript:
S = ' Abcdefghijk ' for I in Range (0,len (S), 2): print S[i]
In this example, we use the Len () function and the range () function to control the loop by using I as the subscript for the S sequence. In the range function, define the upper limit, the lower limit, and the step size of each cycle. This is similar to the For loop in the C language.
Enumerate ()
With the enumerate () function, you can get subscripts and elements at the same time in each loop:
S = ' Abcdefghijk ' for (Index,char) in enumerate (s): print index print Char
In fact, enumerate () returns a fixed value table (tuple) with two elements in each loop, with two elements assigned to index and Char
Zip ()
If you have multiple equal-length sequences, and then want to remove an element from each sequence each time you loop, you can use ZIP () to easily implement:
Ta = [1,2,3]TB = [9,8,7]TC = [' A ', ' B ', ' C ']for (a,b,c) in Zip (TA,TB,TC): print (A,B,C)
Each time the loop is taken, an element is pulled from left to right from each sequence, merged into a tuple, and the elements of the tuple are given to A,b,c
The function of the zip () function is to remove an element from multiple lists, in turn. Each extracted element (from a different list) is composited into a tuple, and the merged tuple is placed in the list returned by the zip (). The zip () function functions as an aggregation list.
We can break up the aggregated list as follows:
Ta = [1,2,3]TB = [9,8,7]
# clusterzipped = Zip (TA,TB) print (zipped)
# decompose
Na, NB = Zip (*zipped)
Print (Na, NB)
Summarize
Range ()
Enumerate ()
Zip ()
Python advanced 05 Loop design