内置函数zip()
2024-08-25 12:46:15
zip有拉链的意思,zip函数像拉链一样将0个或多个可迭代对象按相同位置组合成一个zip对象,该zip对象的每个元素是由每个可迭代对象的相同位置的元素组成的元祖。
如果zip中有多个序列,而各序列的长度不同,那么返回的对象的长度以最短为准,超出的部分不返回。
如果zip中只有一个序列,则返回对象的每个元祖中只有一个元素。如果zip没有给参数,那么返回一个空对象。
用法:
zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9,10]
>>> zip(a,b)
<zip object at 0x00000000027D2FC8>
>>> z=zip(a,b)
>>> print(z)
<zip object at 0x00000000027D6088>
>>> for i in z:
... print(i)
...
(1, 4)
(2, 5)
(3, 6)
>>> x=zip(a)
>>> for i in x:
... print(i)
...
(1,)
(2,)
(3,)
>>> y=zip(a,b,c)
>>> for i in y:
... print(i)
...
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)
另外zip函数可以使用星号解开zip对象,即unzip。
zip() in conjunction with the * operator can be used to unzip a list.
>>> m=zip(*zip(a,b,c))
>>> for i in m:
... print(i)
...
(1, 2, 3)
(4, 5, 6)
(7, 8, 9)
参考:https://docs.python.org/3/library/functions.html#zip
最新文章
- QQ右下角图标不见了
- go sample - hello world
- STL_关联容器 VS C++ hashmap
- JavaWeb chapter 4 Servlet处理HTTP请求
- Html之初体验
- 【C#】窗体动画效果
- TOM大叔的几道Javascript题目与解答
- PHP错误处理及异常处理笔记
- 在Java中怎样把数组转换为ArrayList?
- 一个简单的PHP登录演示(SESSION版 与 COOKIE版)
- Gradle构建Java Web应用(转)
- memset memcpy函数
- [CodeForces 11D] A Simple Task - 状态压缩入门
- 有效防止softmax计算时上溢出(overflow)和下溢出(underflow)的方法
- 面试官:你分析过SpringMVC的源码吗?
- ElasticSearch(五) Elasticsearch-jdbc实现MySQL同步到ElasticSearch
- Django中的forms一些小点
- 上周日选拔题部分write up
- [smarty] 在smarty模板中使用smarty变量初始化 javascript 变量的问题
- 轻量ORM-SqlRepoEx (十四)最佳实践之Dapper(1)