📜  Python zip()

📅  最后修改于: 2020-09-20 04:40:07             🧑  作者: Mango

zip() 函数接受可迭代项(可以为零或更多),将它们聚合到一个元组中,然后将其返回。

zip() 函数的语法为:

zip(*iterables)

zip()参数

Parameter Description
iterables can be built-in iterables (like: list, string, dict), or user-defined iterables

推荐阅读: Python迭代器,__ iter__和__next__

从zip()返回值

zip() 函数基于可迭代对象返回元组的迭代器。

  1. 如果我们不传递任何参数,则zip()返回一个空的迭代器
  2. 如果传递了单个iterable,则zip()返回元组的迭代器,每个元组只有一个元素。
  3. 如果传递了多个Iterable,则zip()返回一个tuple的迭代器,其中每个tuple都具有来自所有Iterable的元素。假设将两个可迭代对象传递给zip() ;一个迭代包含三个元素,另一个包含五个元素。然后,返回的迭代器将包含三个元组。这是因为迭代器在最短的可迭代量耗尽时停止。

示例1: Python zip()

number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']

# No iterables are passed
result = zip()

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

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

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

输出

[]
{(2, 'two'), (3, 'three'), (1, 'one')}

示例2:不同数量的可迭代元素

numbersList = [1, 2, 3]
str_list = ['one', 'two']
numbers_tuple = ('ONE', 'TWO', 'THREE', 'FOUR')

# Notice, the size of numbersList and numbers_tuple is different
result = zip(numbersList, numbers_tuple)

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

result = zip(numbersList, str_list, numbers_tuple)

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

输出

{(2, 'TWO'), (3, 'THREE'), (1, 'ONE')}
{(2, 'two', 'TWO'), (1, 'one', 'ONE')}

* 运算符可与zip()结合使用以解压缩列表。

zip(*zippedList)

示例3:使用zip()解压缩值

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)

输出

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