Python zip()

The zip() function takes iterables (can be zero or more), aggregates them in a tuple, and returns it.

举个例子:

1
2
3
4
5
6
7
languages = ['C++', 'Python']
versions = [2,6]

result = zip(languages, versions)
print(list(result))

# Output: [('C++', 2), ('Python', 6)]

zip() 函数的输入是多个迭代器对象,输出一个zip对象,它是一个tuple迭代器(iterator of tuples),将输入的迭代器中的每个元素一一配对;如果每个迭代器长度不一致,则其输出输入迭代器中最短的那个。

1
2
3
4
5
6
7
languages = ['C++', 'Python']
versions = [2,6,7,8,9]

result = zip(languages, versions)
print(list(result))

# Output: [('C++', 2), ('Python', 6)]

更多例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']

# 0. No iterables are passed
result = zip()

# Converting iterator to list
result_list = list(result)
print(result_list)

# 1. One iterables are passed
result = zip(number_list)

# Converting iterator to list
result_list = list(result) #DO NOT equal [result]!!!
print(result_list)

# 2. Two iterables are passed
result = zip(number_list, str_list)

# Converting iterator to set
result_list = list(result)
print(result_list)

# 3. Two iterables are passed
result = zip(number_list, str_list)

# Converting iterator to set
result_set = set(result)
print(result_set)

输出:

1
2
3
4
[] #空列表中无元组
[(1,), (2,), (3,)] #列表中元组长度为1
[(1, 'one'), (2, 'two'), (3, 'three')] #列表中元组长度为2
{(1, 'one'), (2, 'two'), (3, 'three')} #字典中元组长度为2

另外,zip() 通常与 * 操作符联合使用,其中 * 操作符起到了解压的作用。

1
2
3
4
5
6
7
8
9
10
11
coordinate = ['x', 'y', 'z']
value = [3, 4, 5]

result = zip(coordinate, value)
result_list = list(result)
print(result_list)

c, v = zip(*result_list)
print('c =', c)
print('v =', v)
print(*result_list)

输出:

1
2
3
4
[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)
('x', 3) ('y', 4) ('z', 5)