This article mainly introduces the loop-related functions range, enumerate, and zip in the python advanced tutorial. These functions are often used with loop programs to complete loops, for more information, see the "loop" section. We have discussed the basic loop Syntax of Python. In this section, we will be exposed to more flexible loop methods.
Range ()
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:
The Code is as follows:
S = 'abcdefghjk'
For I in range (0, len (S), 2 ):
Print S [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.
Enumerate ()
Using the enumerate () function, you can get the subscript and element in each loop at the same time:
The Code is as follows:
S = 'abcdefghjk'
For (index, char) in enumerate (S ):
Print index
Print char
In fact, in each cycle of enumerate (), a value table (tuple) containing two elements is returned.
Zip ()
If you want to extract one element from multiple equi-length sequences in each cycle, you can use zip () to conveniently implement the following:
The Code is as follows:
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)
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 break down the aggregated list as follows:
The Code is as follows:
Ta = [1, 2, 3]
Tb = [9, 8, 7]
# Cluster
Zipped = zip (ta, tb)
Print (zipped)
# Decompose
Na, nb = zip (* zipped)
Print (na, nb)
Summary
Range ()
Enumerate ()
Zip ()