Home  >  Article  >  Backend Development  >  What is zip function in python?

What is zip function in python?

藏色散人
藏色散人Original
2019-06-22 09:22:0514149browse

What is zip function in python?

What is zip function in python?

The zip() function in python is used to take an iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return an object composed of these tuples. The advantage of this is that it saves a lot of memory.

If the number of elements of each iterator is inconsistent, the length of the returned list is the same as the shortest object

Related recommendations: "Python Tutorial"

Syntax

zip([iterable, ...])

Parameters: iterable is one or more iterators

Return value: An object is returned, and list() conversion can be used to output a list

1. Example 1

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> zip(a, b)
<zip object at 0x0000000003BB4188>
>>> list(zip(a, b))
[(1, 4), (2, 5), (3, 6)]
>>> 
>>> 
>>> c = [4, 5, 6, 7, 8]
>>> list(zip(a, c))
[(1, 4), (2, 5), (3, 6)]
>>>

2. Example 2

Two lists of equal length are merged into a dictionary: keys = ["A", "B", "C"], values ​​= ["1", "2", "3"], requirement: merge into {"A":1, "B":2, "C" :3}, please use one line of code to implement the

idea: first use the zip() function to pack the two lists into a tuple object, and then use dict to construct the dictionary, so the code is

print(dict(zip(keys, values)))

Run result:

{&#39;B&#39;: &#39;2&#39;, &#39;A&#39;: &#39;1&#39;, &#39;C&#39;: &#39;3&#39;}

The above is the detailed content of What is zip function in python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn