欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python中的zip方法

Python基础 迷途小书童 3年前 (2020-09-17) 2025次浏览 0个评论

软硬件环境

  • windows 10 64bit
  • anaconda3 with python 3.7

视频看这里

此处是youtube的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。

简介

zip()python中的一个内置函数,它接受一系列可迭代对象作为参数,将不同对象中相对应的元素(根据索引)打包成一个元组tuple,返回一个zip对象,可以通过listzip对象转化为list对象。我们来看看zip的函数定义

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.

由上述可知,如果传入的参数的长度不同,元组的个数和传入参数中最短对象的长度一致

zip函数使用示例

最后来看看几个示例

In [1]: aList = [1, 2, 3, 4, 5]

In [2]: bList = [5, 4, 3, 2, 1]

In [3]: a = zip(aList)

In [4]: type(a)
Out[4]: zip

In [5]: list(a)
Out[5]: [(1,), (2,), (3,), (4,), (5,)]

In [6]:

可以看到a的数据类型是zip,然后通过list转化,就可以看到以元组为元素的列表了。上例中zip函数只有一个参数,所以元组中也只有一个元素

In [7]: bList = [5, 4, 3, 2, 1]

In [8]: b = zip(aList, bList)

In [9]: list(b)
Out[9]: [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]

In [10]:

当我们给zip传入2个可迭代参数时,元组中的元素就有2个了

In [16]: cList = [8, 8, 8]

In [17]: aList = [1, 2, 3, 4, 5]

In [18]: c = zip(aList, cList)

In [19]: list(c)
Out[19]: [(1, 8), (2, 8), (3, 8)]

In [20]:

上面中的cList只有3个元素,而aList有5个元素,因此,zip对象中的元组个数跟cList的元素个数一样,都是3个

喜欢 (0)

您必须 登录 才能发表评论!

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

请关闭 Adblock 等类似浏览器插件,然后刷新页面访问,感谢您的支持!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.