What is zip function in python?

藏色散人
Release: 2019-07-10 13:18:12
Original
14183 people have browsed it

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, ...])
Copy after login

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)]
>>>
Copy after login

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)))
Copy after login

Run result:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!