打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python中的 zip() 函数及用法

大家好,我是老马的程序人生~

zip() 函数是 Python 内置函数之一,通过下面的例子,我们对该函数进行总结。

zip(iter1 [,iter2 [...]]):用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象。

*:可把zip的数据释放出来,即解压。

x = [111213]
y = [212223]
zipped = zip(x, y)
print(zipped)  # <zip object at 0x00000269D83F2948>
print(type(zipped))  # <class 'zip'>
print(*zipped)  # (11, 21) (12, 22) (13, 23)

a, b = zip(*zip(x, y))
print(list(a))  # [11, 12, 13]
print(list(b))  # [21, 22, 23]

可以通过*来查看打包之后的内容,也可以通过列表推导式来查看打包之后的内容。

【例子】

x = [123]
print(*zip(x)) # (1,) (2,) (3,)
print([x for x in zip(x)]) # [(1,), (2,), (3,)]

【例子】

x = [123]
y = [456]
z = [789]
print(*zip(x, y, z)) # (1, 4, 7) (2, 5, 8) (3, 6, 9)
print([x for x in zip(x, y, z)]) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

如果各个迭代器的元素个数不一致,那么返回列表长度与最短的对象相同。

【例子】

l = [111213]
t1 = (212223)
t2 = (2122232425)
print([x for x in zip(l, t1)]) # [(11, 21), (12, 22), (13, 23)]
print([x for x in zip(l, t2)]) # [(11, 21), (12, 22), (13, 23)]

d = {312324335}
print([x for x in zip(d.keys(), d.values())]) # [(31, 2), (32, 4), (33, 5)]

p = "python"
s = "shell"
print([x for x in zip(p, s)])
# [('p', 's'), ('y', 'h'), ('t', 'e'), ('h', 'l'), ('o', 'l')]

我们可以使用 list()tuple()dict()来转换来输出对应的类型。

【例子】

a = [123]
b = [456]
print(list(zip(a, b)))  # [(1, 4), (2, 5), (3, 6)]
print(dict(zip(a, b)))  # {1: 4, 2: 5, 3: 6}
print(tuple(zip(a, b)))  # ((1, 4), (2, 5), (3, 6))

zip(*zipped)*zipped参数,可以list数组(数组中的元素都是可迭代对象),也可以是zip()函数返回的解压对象。

【例子】

x = [[123], [456], [789]]

print(*x) # [1, 2, 3] [4, 5, 6] [7, 8, 9]
print(type(zip(*x))) # <class 'zip'>
print(list(zip(*x))) # [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

【例子】

x = ["abc""def""ghi"]
print(*x)  # abc def ghi
print(type(zip(*x)))  # <class 'zip'>
print(list(zip(*x)))
# [('a', 'd', 'g'), ('b', 'e', 'h'), ('c', 'f', 'i')]

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python中zip是什么函数
python实现矩阵转置的几种方法
python循环zip与enumerate
python3中的zip()、zip(*)、list()之间的灵活转换!
Python zip函数及用法
Python|zip函数-求最长公共前缀
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服