English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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)
Parameters | Description |
---|---|
iterables | Can be built-in iterable items (such as: list, string, dictionary) or user-defined iterable items |
Recommended reading: Python iterator, __iter__ and __next__
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.
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')}
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)
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)