Python(7) zip()

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.

简单来说呢,zip函数是将传入的一系列iter里面的元素重新组织成为tuple,第i个tuple是由所有iter的第i个元素共同组成。当iter的长度如果不相同的话,那么返回的list的长度和长度最短的iter的长度相同。注意zip()返回的是一个zip ojbect,如果想取出里面的值,必须要用到next()

# 什么都不传入
res = []
for i in zip():
    res.append(i)
print(res)
#输出:[]
# 只传入一个iter
x = [1, 2, 3]
res = []
for i in zip(x):
    res.append(i)
print(res)
#输出:[(1,), (2,), (3,)]
# 传入多个长度相同的iter
x = [1, 2, 3]
y = [4, 5, 6]
z = [7, 8, 9]
res = []
for i in zip(x,y,z):
    res.append(i)
print(res)
#输出: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
# 传入多个长度不同的iter
x = [1, 2, 3]
y = [4, 5, 6, 7]
z = [8, 9, 10, 11, 12]
res = []
for i in zip(x, y, z):
    res.append(i)
print(res)
#输出:[(1, 4, 8), (2, 5, 9), (3, 6, 10)]
# unzip 
res = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
for i in zip(*res):
    print(i)
#输出: (1, 2, 3)\n(4, 5, 6)\n(7, 8, 9)

这个过程,还可以理解为矩阵转置
res = [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
for i in zip(*zip(*res)):
    print(i)
#输出:(1, 4, 7)\n(2, 5, 8)\n(3, 6, 9) 

在函数调用中使用*list/tuple的方式表示将list/tuple分开,作为位置参数传递给对应函数
所以zip(*res)<=>zip((1, 4, 7), (2, 5, 8), (3, 6, 9))

虽然zip()函数返回的是一个zip object,无法通过直接print的方式来打印出值。但是可以被转换掉,特别是可以转换成字典,不过当转换成字典的时候,iter的数量要 2

x = [1, 2, 3]
y = [4, 5, 6, 7]
print(list(zip(x,y))) # [(1, 4), (2, 5), (3, 6)]
print(dict(zip(x,y))) # {1: 4, 2: 5, 3: 6}
# 有人用map方法做,不过在python3.x里面map返回的是一个map object,所以同样不能直接打印出来,但是还是可以用list做嵌套唷,不过这样是不是有点脱裤子。。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值