This article comes from machine learning algorithms and Python combat, the author loves learning hutong

Zip () function

Take a look at the syntax:

Zip (iter1 [,iter2 [...]]) - > zip ObjectCopy the code

Python’s built-in help() module provides a brief but somewhat confusing explanation:

Returns a tuple iterator where the i-th tuple contains the i-th element in each argument sequence or iterable. When the shortest iterable input is exhausted, the iterator stops. Using a single iterable argument, it returns a 1-tuple iterator. With no arguments, it returns an empty iterator.

As always, this module is useful when you are proficient in more general computer science and Python concepts. For starters, however, this passage only raises more questions. Let’s try to explain zip() functionality with examples, snippets, and visualizations: get elements from many iterations, and then… Put together

We can demonstrate the functionality of zip() with several lists:

uppercase = ['A', 'B', 'C']
lowercase = ['a', 'b', 'c']


for x, y in zip(uppercase, lowercase):
    print(x, y)
Copy the code

Output:

A a
B b
C c
Copy the code

However, instead of being limited to two iterables passed as arguments – we can add as many as we want:

uppercase = ['A', 'B', 'C']
lowercase = ['a', 'b', 'c']
numbers = [1, 2, 3]


for x, y, z in zip(uppercase, lowercase, numbers):
    print(x, y, z)
Copy the code

This will print:

A a 1
B b 2
C c 3
Copy the code

Let’s take a visual look at how the zip() function works in Python:

Another important caveat of the zip() function is that if the number of elements in each iterator is inconsistent, it returns the same list length as the shortest object:

uppercase = ['A', 'B', 'C', 'D', 'E']
lowercase = ['a', 'b', 'c', 'd']
numbers = [1, 2, 3]


for x, y, z in zip(uppercase, lowercase, numbers):
    print(x, y, z)
Copy the code

Output:

A a 1
B b 2
C c 3
Copy the code

As we can see, uppercase and lowercase lists have 5 and 4 elements, even though three triples are listed.

The important thing to know is what the zip() function returns.

Although it looks like you get a list when you call this function, it actually returns a special data type called ZIP Object, which means you can’t browse with an index. Let’s learn how to convert this to other data types (such as lists).

Before that, we should also learn the concepts of Iteration, iterable and iterator:

  • Iteration is a common term in computer science. It refers to performing an operation on a set of elements, one element at a time. A good example is loops – which apply to each individual project until the entire set of projects has run.
  • Iterable is an object that can be iterated over. Iterable is an object that produces iterators.
  • Iterator is an object representing a data stream that returns data one element at a time. It also remembers its position in the iteration. Essentially, it controls how the iterable should be iterated over.

Convert zip() objects to lists (and use indexes)

The zip() function returns a zip object (similar to the map() operation).

The ZIP object provides some interesting functionality (iterating faster than a List), but we often need to convert it to a list. To do this, we need to call the list() function:

b = ["red", "green", "blue"]
c = ["leopard", "cheetah", "jaguar"]


print(list(zip(b, c)))
Copy the code

Output:

[('red', 'leopard'), ('green', 'cheetah'), ('blue', 'jaguar')]
Copy the code

The list() function converts the ZIP object to a list of tuples. We can use the index to navigate through individual tuples. For readability, we first assign the new list to a variable:

b = ["red", "green", "blue"]
c = ["leopard", "cheetah", "jaguar"]
new_list = list(zip(b, c))
print(new_list[0])
print(new_list[1])
print(new_list[2])
Copy the code

This will print:

('red', 'leopard')
('green', 'cheetah')
('blue', 'jaguar')
Copy the code

Convert the zip() object into a dictionary

In addition, the dict() function can be used to turn zip objects into dictionaries. Note that only two zip() arguments can be used – the former produces a key and the latter a value:

b = ["red", "green", "blue"]
f = ["strawberry", "kiwi", "blueberry"]


print(dict(zip(b, f)))
Copy the code

Output:

{'red': 'strawberry', 'green': 'kiwi', 'blue': 'blueberry'}
Copy the code

Unpack the list

In some cases, we need to do the opposite — unzip the iterator. Decompression involves restoring the compressed element to its original state. To do this, we add the * operator to the function call. Ex. :

a = [1, 2, 3]
b = [4, 5, 6]
zipped = zip(a, b)
list(zipped)


a2, b2 = zip(*zip(a, b))
print(a == list(a2) and b == list(b2))
Copy the code

Output:

True
Copy the code

Zip vs. list generation (potential problem with for loops)

Visualization of the zip () function used with Python’s for loop

Notice missing elements after applying the for loop!

Another great Python feature, list comprehensions, can be used in conjunction with the zip() function. On the surface it looks simple…

m = ["mind", "mouse", "mini"]
n = ["norm", "night", "necklace"]


[print(a, b) for a, b in zip(m, n)]
Copy the code

Output:

mind norm
mouse night
mini necklace
Copy the code

It looks so simple, there doesn’t seem to be any mistakes, right? Yes.

If we want a to get the argument from the list generator and print it out, we get a NameError, which is perfectly normal because A is not a real number outside of the list derivation:

Traceback (most recent call last):
  File "C:\Pro\Py\tp-ex\tmp1.py", line 5, in 
    print(a)
NameError: name 'a' is not defined
Copy the code

However, if we decide to use a for loop instead of a list generator, and then print a, we get some strange results. Remember, the for loop outputs the same result as the list generator.

m = ["mind", "mouse", "mini"]
n = ["norm", "night", "necklace"]




for m, n in zip(m, n):
    print(m, n)


print(m)
Copy the code

The resulting output is…

mind norm
mouse night
mini necklace
mini
Copy the code

Wait, what is rebel Mini doing here? It turns out that the list variables “mind”, “mouse”, “mini” that M referenced earlier were overwritten! Therefore, keep in mind that list generation and for loops run completely differently.

conclusion

As it turns out, the zip() function does have some tricks in Python! ???? As always, you are encouraged to actually use our code examples, not just read this article. If you interact with code and tweak it, you’re bound to encounter some unique problems — solving them will help you master your knowledge better.

Original text: blog.soshace.com/python-zip-…

By Denis Kryukov 

Note: the menu of the official account includes an AI cheat sheet, which is very suitable for learning on the commute.

Highlights from the past2019Machine learning Online Manual Deep Learning online Manual AI Basic Download (Part I) note: To join our wechat group or QQ group, please reply "add group" to join knowledge planet (4500+ user ID:92416895), please reply to knowledge PlanetCopy the code

Like articles, click Looking at the