Python zip()

zip()

zip(*iterables) --> 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.

a = [1,2,3,4]
b = [5,6,7,8]
c= [9,10,11]

print(zip(a,b))
>> <zip object at 0x00000212B395F048> # 返回zip对象

# 转换为列表
print(list(zip(a,b)))
>> [(1, 5), (2, 6), (3, 7), (4, 8)]
print(list(zip(a,c)))
>> [(1, 9), (2, 10), (3, 11)] # 与最短的列表保持一致
print(list(zip(a,b,c)))
>> [(1, 5, 9), (2, 6, 10), (3, 7, 11)]
print(list(zip(a,c,b)))
>> [(1, 9, 5), (2, 10, 6), (3, 11, 7)]

# 转换为字典
print(dict(zip(a,b)))
>> {1: 5, 2: 6, 3: 7, 4: 8}

a, b = zip(*zip(a,b))          # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
print(a)
>> (1, 2, 3, 4)
print(b)
>> (5, 6, 7, 8)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值