Environment: Python 3.5.1
CentOS 7
A zip function can traverse two iterators at the same time.
When you write Python code, you typically face many lists, and the objects in those lists may be interrelated. The following example:
names = [' Cecilia ', ' Lily ', ' Maria '] length = [Len (word) for word in Names]
For the source list and derived list in the example above, there is an association at the same index, which can be extended to an example:
Longest_name = None Max_length = 0 for i in range (len (names)): Count = length[i] if count > Max _length:longest_name = names[i] Max_length = Count print (longest_name) >>&G T Cecilia
The problem with the above code is that the entire loop statement looks messy. Using subscripts to access names and length makes the code difficult to read. Switching to enumerate can alleviate the problem slightly, but it is still not ideal.
For I, name in enumerate (names): Count = length[i] if count > max_length:longest_name = Name Max_length = Count
Using the python built-in zip function will make the above code concise. In Python 3, the zip function can encapsulate two or more two iterators in the genetic builder. This zip generator obtains the next value of the iterator from each iterator, and then aggregates the values into tuples (tuple).
For name, count in zip (names, length): if count > max_length:longest_name = name max_length = Count
In addition, the Python 3 built-in zip function has a problem, if the input iterator length is different, zip will behave very strange. For example, when a name is added to names, but the length is not updated. Now, if you use zip to traverse these two lists at the same time, you will have unexpected results.
Names.append (' Song ') for name, count in zip (names, length): Print (name) >>> Cecilia Lily Maria
The new element ' song ' does not appear in the traversal results. In those iterators that are encapsulated, as long as one is exhausted, the zip will no longer produce tuples. If the length of the iterator to be traversed is different, the zip terminates prematurely. If you are unsure if the list of zip packages is equal, consider using the zip_longest function in the itertools built-in module.
Effective Python Small note zip function