📅  最后修改于: 2020-09-20 04:40:07             🧑  作者: Mango
zip()
函数的语法为:
zip(*iterables)
Parameter | Description |
---|---|
iterables |
can be built-in iterables (like: list, string, dict), or user-defined iterables |
推荐阅读: Python迭代器,__ iter__和__next__
zip()
函数基于可迭代对象返回元组的迭代器。
zip()
返回一个空的迭代器zip()
返回元组的迭代器,每个元组只有一个元素。 zip()
返回一个tuple的迭代器,其中每个tuple都具有来自所有Iterable的元素。假设将两个可迭代对象传递给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')}
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)
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)