Python3---内建函数---zip()
前言
该文章描述了函数zip()的使用
2020-01-16
天象独行
0X01;查看zip()使用方法
#!/uer/bin/env python #coding:utf-8 help(zip)
Help on class zip in module builtins: class zip(object) | zip(*iterables) --> zip object | | Return a zip object whose .__next__() method returns a tuple where | the i-th element comes from the i-th iterable argument. The .__next__() | method continues until the shortest iterable in the argument sequence | is exhausted and then it raises StopIteration. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature.
0X02;描述
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
我们可以使用 list() 转换来输出列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
注释:Python2 的返回值为元组
0X03;语法
zip([iterable,...])
参数:iterabl -- 一个或多个迭代器;
0X04;返回值
返回一个对象
0X05;实例
1;Python2
>>> a = [1,2,4] >>> b = [3,4,5] >>> zip(a,b) [(1, 3), (2, 4), (4, 5)] >>>
2;Python3
>>> a = [3,1,4] >>> b = [2,5,6] >>> zip(a,b) <zip object at 0x7f4afcaa7be0> >>>