Python function | zip function explained

Hello, my friends, I am very happy to share technical articles with you here. I am Amo Xiang, an employee of a working company, which is Amoderived from the English name of the previous company . As a novice who has just entered the Internet industry for a few years, bloggers write blogs to record their own learning process and the mistakes they have made, but also hope to help many young people who are in the initial stage and let them go less. detour. When writing the article, I refer to a large number of books and the resources of some Internet giants, combined with his own work experience. The bloggers are scientific and rigorous, and strive for excellence, but omissions are inevitable. Friends criticize and correct. Blog homepage: https://blog.csdn.net/xw1680?spm=1011.2124.3001.5113

1. Introduction to the zip() function

1.1 Function

The zip() function is used to take the iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return the zip object composed of these tuples.

1.2 Grammar

zip(*iterables) --> zip object

Parameter Description:

(1) iterables: Iterable objects, such as lists, dictionaries, tuples, strings, etc. The zip() function allows multiple iterable objects as parameters.
(2) When the zip() function has no parameters, it returns an empty iterator.
(3) When the zip() function has only one parameter, one element in turn is taken from the parameters to form a tuple, and the tuples formed in turn are combined into a new iterator.
(4) When the zip() function has two parameters, one element is taken from the two parameters to form a tuple, and the tuples formed in turn are combined into a new iterator.
(5) Return value: Return an iterable zip object, whose internal elements are tuples, which can be converted into lists or tuples using the list() function or tuple() function.

2. Application of zip() function

2.1 Use the zip() function to merge lists

The following uses the zip() function to merge the two lists. For example, to merge two lists of name_list and age_list, the code is as follows:

name_list = ["Amo", "Paul", "Jason", "Seven"]
age_list = [18, 19, 20, 21]
# 输出 ==> [('Amo', 18), ('Paul', 19), ('Jason', 20), ('Seven', 21)]
print(list(zip(name_list, age_list)))

2.2 Use the zip() function to build a dictionary

There are two lists name_list and score_list. The name_list stores the student names, and the score_list stores the test scores of each student. If you want to find the test scores by a certain student name, you need a dictionary. The zip() function can be very Conveniently build a dictionary, the code is as follows:

name_list = ["Amo", "Paul", "Jason", "Seven"]  # 定义列表name_list
score_list = [80, 96, 77, 88]  # 定义成绩
my_dict = dict(zip(name_list, score_list))  # 使用dict()函数将zip对象转换为字典
print(my_dict["Amo"])  # 输出 80

2.3 The magical use of zip() function 1-matrix rotation

Matrix is ​​a common tool in advanced mathematics, and it is also often used in statistical analysis and mathematical applications. The following uses the zip() function to realize the rotation of an xyz matrix, the code is as follows:

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

xyz = list(zip(x, y, z))
print(xyz)  # 输出 ==> [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

2.4 The magic of the zip() function 2-the row and column transpose of the matrix

The transposition of a matrix is ​​an operation of a matrix, and it occupies an important position in all the operations of the matrix. For example, the matrix produced by exchanging the rows and columns of matrix A is called the transposed matrix of A, and this process is called matrix transpose. The following implementation transposes the xyz matrix, the code is as follows:

x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]

xyz = list(zip(x, y, z))
print(xyz)
for a, b, c in zip(x, y, z):
    print(f"{a},{b},{c}")

2.5 The magic of the zip() function 3— Transpose a 4×3 matrix into a 3×4 matrix

data1 = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11))
data2 = zip(*data1)
print(type(data2))  # <class 'zip'>
print(tuple(data2))  # 输出 ==> ((0, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11))

2.6 Perform the reverse operation of the zip() function by decompressing the sequence

In some cases, we need to perform the opposite operation-the decompression sequence. The decompression operation involves restoring the compressed element to its original state. You can add the * operator to the function call. code show as below:

a = (1, 2, 3)
b = (10, 20, 30)
L = list(zip(a, b))
print(f"obj = {L}")
c, d = list(zip(*L))  # 使用*解压序列
print(f"c = {c} \nd = {d}")
if a == c and b == d:
    print("两次 zip() 等于啥都没干......")

2.7 Output the key corresponding to the largest value in the dictionary

In a dictionary, the zip() function comes in handy when evaluating the key corresponding to the largest value. code show as below:

data = {
    
    "张三": 100, "李四": 20, "王五": 500, "赵六": 12}
obj = zip(data.values(), data.keys())
# 输出:分数最高的学生姓名为: 王五
print(f"分数最高的学生姓名为: {max(obj)[1]}")

Thank you for reading this blog post, and hope this article can be your leader in programming. I wish you a happy reading!


Insert picture description here

    A good book never gets tired of reading a hundred times. And if I want to be the most beautiful boy in the audience, I must insist on acquiring more knowledge through learning, use knowledge to change my destiny, use blog to witness growth, and use actions to prove that I am working hard.
    If my blog help you, if you like my blog, please 点赞, 评论,收藏 a key triple Oh! I heard that people who like it won’t have bad luck and will be full of energy every day! If you really want to be a prostitute, I wish you happy every day, and welcome to my blog.
 Coding is not easy, and your support is my motivation to stick to it. After the thumbs do not forget 关注me!

Guess you like

Origin blog.csdn.net/xw1680/article/details/110948264
Recommended