Use of the Python zip function

zip is a built-in function of python that can be used directly

What Python zip does

Recombine elements from multiple lists into a new

Note that python2x returns a list, and python3x returns an object

Write the following two lists to merge

a = [1, 2, 3]
b = (4, 5, 6)
c = zip(a, b)
print(c)  # 打印结果:<zip object at 0x0000023856F7A480>
print(list(c)) # 转成list 打印结果:[(1, 4), (2, 5), (3, 6)]

If you want to fill out the list is no problem

a = [1, 2, 3]
b = (4, 5, 6)
c = [7, 8, 9]
d = zip(a, b, c)
print(list(d))  # 转成list 打印结果:[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

After the data is used, we can convert it to the format we want, such as converting it into a dictionary

a = [1, 2, 3]
b = (4, 5, 6)
c = zip(a, b)
print(dict(c))  # 转成字典 打印结果:{1: 4, 2: 5, 3: 6}

Precautions:

When the number of elements in multiple sequences is inconsistent, the shortest sequence will be used for compression

a = [1, 2, 3]
b = (4, 5, 6, 7, 8, 9)
c = zip(a, b)
print(list(c))  # 转成list打印结果:[(1, 4), (2, 5), (3, 6)]

Guess you like

Origin blog.csdn.net/qq_33210042/article/details/131600472