python-基础语法-zip()函数
2018-10-04 15:59
423 查看
0.函数功能
作用:在一个或多个对象中,将对应的元素打包成一个元组
参数:以可迭代的对象作为参数
返回值:在python3中,返回这些元组组成的对象;在python2中,返回这些元组组成的列表
注意:如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同。利用 * 号操作符,可以将元组解压为列表。
[code]class zip(object) | zip(iter1 [,iter2 [...]]) --> 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.
1.代码示例
[code]lowercase_letter = [chr(i) for i in range(97,123)] print(lowercase_letter) #result:['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] uppercase_letter = [chr(i) for i in range(65,91)] print(uppercase_letter) #result:['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] for (ch,CH) in zip(lowercase_letter[:5],uppercase_letter[:10]): print((ch,CH),end=' ') #result:('a', 'A') ('b', 'B') ('c', 'C') ('d', 'D') ('e', 'E')
代码首先生成了“小写字母”和“大写字母”两个列表,之后通过zip()函数组合起来。
由于“小写字母”列表只取了前5个值,所以最终结果也只匹配了最短列表中的元素。
2.zip()函数的生存周期
zip()函数返回的是一个对象,在使用的时候,要注意生存周期的问题,比如:
[code]a = [1,2,3] b = [4,5,6] z = zip(a,b) print(list(z)) print(list(z))
由于z是一个对象,在打印之前,需要先转换为list。
从结果上看,当我们第二次调用list(z),这时候的z已经为空了。
阅读更多相关文章推荐
- 1.python语法基础-列表、数组、函数、元组和控制语句
- python基础语法(8) 函数3
- python zip函数基础
- Python入门基础语法之序列、字典、函数、递归
- Python基础语法(2)——字典、函数定义使用、控制流(if&for&while)
- Python语法基础19.函数(二)
- Python基础语法学习----列表的访问,操作以及列表函数
- Python基础语法05--函数模块
- Python基础语法——函数(四)
- Python语法基础20.函数(三)
- [Python]基础语法(三)常见函数网站
- Python入门基础(3)——函数参数与语法结构
- 4-python基础python的基本语法之标准输入函数
- python语法基础归纳(3)--函数
- Python语法基础(九):函数
- Python连载系列之Python语法基础2:Python中的函数
- python基础语法(6) 函数1
- Python基础语法——函数(一)
- Python基础语法——函数(二)
- [Python]基础语法(二)文本处理函数