Author: vamei Source: http://www.cnblogs.com/vamei welcome reprint, please also keep this statement. Thank you!
Previously, in the "loop" section, we have discussed the most basic loop Syntax of Python. In this section, we will be exposed to more flexible loop methods.
1. ExploitationRange (), GetSubscript
In python, if the in after a for loop follows a sequence, the sequence elements used for each loop are not the subscript of the sequence.
We have used range to control the for loop before. Now, we continue to develop the range Function to control the loop by Subscript:
S ='Abcdefghjk'ForIInRange (0, Len (s), 2):PrintS [I]
In this example, we use Len () and range () Functions and I as the subscript of the S sequence to control the loop. In the range function, the upper limit, lower limit, and step size of each loop are defined respectively. This is similar to the for loop in C.
2. ExploitationEnumerate ()And getSubscript and Element
Using the enumerate () function, you can get the subscript and element in each loop at the same time:
S ='Abcdefghijk'For(Index, char)InEnumerate (s ):PrintIndexPrintChar
In fact, in each cycle of enumerate (), a value table (tuple) containing two elements is returned.
3. ExploitationZip (), ImplementationParallel Loop
If you want to extract one element from multiple equi-length sequences in each cycle, you can use zip () to conveniently implement the following:
Ta = [1, 2, 3] TB= [9, 8, 7] Tc= ['A','B','C']For(A, B, C)InZip (TA, TB, Tc ):Print(A, B, C)
In each loop, an element is extracted from left to right from each sequence and merged into a tuple. Then, the tuple elements are assigned to A, B, and C.
The zip () function extracts one element from multiple lists in sequence. The elements extracted each time (from different lists) are combined into a single tuple, And the merged tuples are placed in the list returned by the ZIP.
The zip () function is used to aggregate the list. We can also break down 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)
Summary:
Range ()
Enumerate ()
zip ()