The seven realms of using the zip function in Python

1 Introduction

There are some built-in functions in Python that can make our code very elegant. zipFunctions are one of them, but the use of the zip function is not very intuitive for beginners and is sometimes error-prone. zip Therefore, this article will explore the concept, usage and skills of powerful functions from 7 levels from the shallower to the deeper .
Without further ado, let's get started!

2. Level 0: Understand the basic syntax of the zip function

zipThe function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return the tuples composed of these tuples iterator.
For example, we can use it to combine two lists in the following way, the sample code is as follows:

id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Bai Li']
record = zip(id, leaders)

print(record)
# <zip object at 0x7f266a707d80>

print(list(record))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Bai Li')]

As shown in the example above, zipthe function returns an iterator of tuples, where the i-th tuple contains the i-th i element in each list.

3. Level 1: The zip function handles multiple objects at the same time

In fact, functions in Python zip have powerful capabilities such as the ability to process any number of iterable items at once, not just two.

First, let's see if we pass a list to zipthe function, the example is as follows:

id = [1, 2, 3, 4]
record = zip(id)
print(list(record))
# [(1,), (2,), (3,), (4,)]

If we pass all three at the same time list , the result is as follows:

id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Bai Li']
sex = ['m', 'm', 'm', 'm']
record = zip(id, leaders, sex)

print(list(record))
# [(1, 'Elon Mask', 'm'), (2, 'Tim Cook', 'm'), (3, 'Bill Gates', 'm'), (4, 'Bai Li', 'm')]

zipAs mentioned above, no matter how many iterables we pass to the function, it works as expected.
By the way, if there are no arguments, zipthe function just returns an empty iterator.

4. Level 2: The zip function handles parameters with different lengths

Real data is not always clean and complete, and sometimes we have to deal with iterables of unequal length. By default, zipthe function's result is based on the shortest iterable.
Examples are as follows:

id = [1, 2]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Bai Li']
record = zip(id, leaders)

print(list(record))
# [(1, 'Elon Mask'), (2, 'Tim Cook')]

As shown in the code above, the shortest list is id such that recordcontains only two tuples, and leaders the last two elements in the list are ignored. What should we do
if the last two are not happy about being ignored? Python will help us again. There is also a function in the module called . As the name suggests, it's a sibling of the function whose result is based on the longest argument. We might as well use a function to generate the above list, the result is as follows:leader
itertools zip_langest zip
zip_langest record

from itertools import zip_longest
id = [1, 2]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Bai Li']

long_record = zip_longest(id, leaders)
print(list(long_record))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), (None, 'Bill Gates'), (None, 'Bai Li')]

long_record_2 = zip_longest(id, leaders, fillvalue='Top')
print(list(long_record_2))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), ('Top', 'Bill Gates'), ('Top', 'Bai Li')]

As mentioned above, zip_langestfunctions return results based on their longest arguments. The optional fillvalueparameter (default value None) can help us fill in missing values.

5. Level 3: Master unzip operation

In the previous example, if we got the list first record, how do we unzipunpack it into individual iterables?
Unfortunately, Python doesn't have a direct decompression unzip function. However, if we are familiar with asterisk * tricks, decompression will be a very simple task.

record = [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Bai Li')]
id, leaders = zip(*record)
print(id)
# (1, 2, 3, 4)
print(leaders)
# ('Elon Mask', 'Tim Cook', 'Bill Gates', 'Bai Li')

In the example above, the asterisk performed the unpacking operation, i.e. unpacking all four tuples from the record list.

6. Level 4: Create and update dict through zip function

zipIt is very convenient to create and update a dict based on a few independent lists, benefiting from the powerful functions .
We can use the following one-linesolutions:
● Use dictionary generation and zip function
● Use dict and zip function
The sample code is as follows:

id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Bai Li']

# create dict by dict comprehension
leader_dict = {
    
    i: name for i, name in zip(id, leaders)}
print(leader_dict)
# {
    
    1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4:'Bai Li'}

# create dict by dict function
leader_dict_2 = dict(zip(id, leaders))
print(leader_dict_2)
# {
    
    1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: 'Bai Li'}

# update
other_id = [5, 6]
other_leaders = ['Larry Page', 'Sergey Brin']
leader_dict.update(zip(other_id, other_leaders))
print(leader_dict)
# {
    
    1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: ''Bai Li'', 5: 'Larry Page', 6: 'Sergey Brin'}

The example above doesn't use forloops at all, how elegant and elegant that is Pythonic!

7. Level 5: Use the zip function in a for loop

Working with multiple iterables at the same time is often a common scenario, and it’s one of my favorite uses of forfunctions when we use functions in loops . Examples are as follows:zipzip

products = ["cherry", "strawberry", "banana"]
price = [2.5, 3, 5]
cost = [1, 1.5, 2]
for prod, p, c in zip(products, price, cost):
    print(f'The profit of a box of {
    
    prod} is £{
    
    p-c}!')
# The profit of a box of cherry is £1.5!
# The profit of a box of strawberry is £1.5!
# The profit of a box of banana is £3!

8. Level 6: Realize matrix transpose

Let's look at the following questions:

How to implement the transpose operation of a matrix elegantly?

Wow, given that we've covered functions zip, asterisks *, and list comprehensions above, one-linethe implementation of is as follows:

matrix = [[1, 2, 3], [1, 2, 3]]
matrix_T = [list(i) for i in zip(*matrix)]
print(matrix_T)
# [[1, 1], [2, 2], [3, 3]]

9. Summary

This article highlights zip various uses of the powerful function in Python, and gives corresponding code examples.
insert image description here

Are you useless?

Guess you like

Origin blog.csdn.net/sgzqc/article/details/128434877
Recommended