您的位置:首页 > 编程语言 > Python开发

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已经为空了。

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: