English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Funções no Python

Tipos de Dados do Python

Python file operations

Python objects and classes

Python date and time

Advanced Python knowledge

Python reference manual

Python zip() usage and examples

Python内置函数

The zip() function accepts iterable items (which can be zero or more), aggregates them into a tuple, and then returns it.

The syntax of the zip() function is:

zip(*iterables)

zip() parameters

ParametersDescription
iterablesCan be built-in iterable items (such as: list, string, dictionary) or user-defined iterable items

Recommended reading: Python iterator, __iter__ and __next__

zip() return value

The zip() function returns an iterator of tuples based on the iterable object.

  • If no parameters are passed, zip() returns an empty iterator

  • If a single iterable is passed, zip() returns an iterator of tuples, each with only one element.

  • If multiple iterables are passed, zip() returns an iterator of tuples, each with elements from all iterables.
    Assuming two iterable variables are passed to zip(); one containing three elements and the other containing five elements. Then, the returned iterator will contain three tuples. This is because the iterator stops when the shortest iterable is exhausted.

示例1Python zip()

number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']
# No iterable parameter
result = zip()
# Convert the iterator to a list
result_list = list(result)
print(result_list)
# 两个iterable
result = zip(number_list, str_list)
# 将迭代器转换为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')
# 注意,numbersList和numbers_tuple的大小不同
result = zip(numbersList, numbers_tuple)
# 转换为set集合
result_set = set(result)
print(result_set)
result = zip(numbersList, str_list, numbers_tuple)
# 转换为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)

Python内置函数