Detailed explanation of zip function in Python3

Introduction to the zip function

In Python 2.x, the zip() function returns a list. In Python3, the zip() function is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples (Tuple), and then return the object composed of these tuples. The advantage of this is to save Quite a lot of memory.

Python's tuples are similar to lists, except that the elements of the tuple cannot be modified. Use parentheses ( ) for tuples and square brackets [ ] for lists .

grammatical format

zip syntax format:

zip([iterable, ...])

Among them, iterable represents one or more iterators. This method returns an object.

example

The following example shows how to use zip:

a = [1, 2, 3]
b = [4, 5, 6]

zipped = zip(a, b)  # 返回一个对象
print(zipped)

# 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
x1, y1 = zip(*zip(a, b))
print(list(x1))
print(list(y1))

A list can be output using the list() transformation.

a = [1, 2, 3]
b = [4, 5, 6]

# list() 转换为列表
zip_list = list(zip(a, b))
print(zip_list)

If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object.

a = [1, 2, 3]
c = [4, 5, 6, 7, 8]

# 元素个数与最短列表一致
print(list(zip(a, c)))

A tuple can be unpacked into a list using the notch operator.

a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]

zipped = zip(a, b)  # 返回一个对象

# 利用 ***** 号操作符,可以将元组解压为列表
print(*zipped)
# 或
print(*zip(a, b))

Contrary to zip, zip(*) can be understood as decompression and returns a two-dimensional matrix:

a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]

# 与zip相反,zip(*) 可理解为解压,返回二维矩阵式
x1, y1 = zip(*zip(a, b))
print(list(x1))
print(list(y1))

In machine learning model training, it is often necessary to shuffle the data set, which can be achieved with the zip() function:

# encoding=utf-8
# 机器学习模型训练中,经常需要打乱数据集,用zip()函数可以实现
import random

# 设置随机种子,保证每次生成随机相同,方便重现
random.seed(1)

x = [1, 2, 3, 4, 5, 6]
y = [0, 1, 0, 0, 1, 1]

# zip打包之后,用list转化为列表
zipped_data = list(zip(x, y))
print("原始数据:%s" % zipped_data)
# 打乱样本的数据,random使用的是原地操作的方式,没有任何返回值
# shuffle:打乱顺序
random.shuffle(zipped_data)
print("乱序数据:%s" % zipped_data)

# zip(*)反向解压,map()逐项转换类型,list()做最后转换
zipped_data2 = list(map(list, zip(*zipped_data)))
print(zipped_data2)

Guess you like

Origin blog.csdn.net/wo541075754/article/details/130461839