zip的使用

zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表

zip 方法在 Python 2 和 Python 3 中的不同:在 Python 3.x 中为了减少内存,zip() 返回的是一个对象。如需展示列表,需手动 list() 转换。

“Return a list of tuples, where each tuple contains the ith element from each of the argument sequences. The returned list is truncated in length to the length of the shortest argument”
其大致意思就是分别提取N个列表的第i个元素组成一个元组,然后再将这些元组作为基本元素构成一个列表,其中列表的长度与最短的列表一致。zip函数的输入对象除列表以外,还可以是元组,但其输出均是以元组为元素的列表

#!/usr/bin/python
# -*- coding: utf-8 -*-

x=(1,2,3)
y=(4,5,6)
z=(7,8,9)

a1=zip(x,y,z)
print("a1={} 针对多个列表使用zip".format(list(a1)))
a2=zip(x)
print("a2={} 一个列表使用zip".format(list(a2)))

X=["a","b"]
a3=zip(x,X)
print("a2={} zip对长度的处理".format(list(a3)))

a4=zip(*zip(x,y))
print("a4={} 解zip过程".format(list(a4)))
---------------------
a1=[(1, 4, 7), (2, 5, 8), (3, 6, 9)] 针对多个列表使用zip
a2=[(1,), (2,), (3,)] 一个列表使用zip
a3=[(1, 'a'), (2, 'b')] zip对长度的处理
a4=[(1, 2, 3), (4, 5, 6)] 解zip过程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值