python中的
zip()
函数是一个非常有用的内建函数,用于将多个可迭代对象(例如:列表、元组、字典等)聚合成一个元组,返回由这些元组组成的对象。
1. zip()用法
1.1 基本用法
zip()
函数用于将多个可迭代对象中的元素按位置组合成元组。下面是一个基本的示例:
a = [1,2,3] b = ["a", "b", "c"] c = zip(a, b) for i in c: print(i)
代码输出:
(1, 'a')
(2, 'b')
(3, 'c')
1.2 不等长的可迭代对象
如果输入可迭代对象长度不同,zip()
会根据最短的可迭代对象来进行压缩,多余的元素将会被丢弃:
list1 = [1, 2, 3] list2 = ('a', 'b') result = zip(list1, list2) print(list(result))
代码输出:
[(1, 'a'), (2, 'b')]
可以看到,list1 中的 3 被丢弃,因为 list2 长度为 2。
1.3 多个可迭代对象
zip()
支持多个可迭代对象。可以将它们按顺序组合在一起
list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] list3 = [true, false, true] result = zip(list1, list2, list3) print(list(result))
代码输出:
[(1, 'a', true), (2, 'b', false), (3, 'c', true)]
1.4 zip和字典
如果传入的可迭代对象是字典,zip()
会按键进行配对。因此,通常会结合 dict()
使用来创建字典。
keys = ['name', 'age', 'city'] values = ['alice', 25, 'new york'] result = zip(keys, values) dictionary = dict(result) print(dictionary)
代码输出:
{'name': 'alice', 'age': 25, 'city': 'new york'}
1.5 解压zip
zip()
生成的结果是一个迭代器, 对于已经压缩的数据我们可以使用 zip(*iterables)
来进行解压缩操作
list1 = [1, 2, 3] list2 = ('a', 'b', 'c') result = zip(list1, list2) # 解压 unpacked = zip(*result) print(list(unpacked))
代码输出:
[(1, 2, 3), ('a', 'b', 'c')]
2. zip() 应用场景
2.1 并行遍历多个序列
zip()
函数常用于并行遍历多个序列,在循环中挨个取出每一个序列中对应元素的位置
names = ['alice', 'bob', 'charlie'] ages = [25, 30, 35] for name, age in zip(names, ages): print(f"{name} is {age} years old.")
2.2 构建字典
如前所述,zip()
和 dict()
结合使用可以非常方便的创建字典
keys = ['name', 'age', 'city'] values = ['alice', 25, 'new york'] result = dict(zip(keys, values)) print(result)
2.3 用于矩阵转置
在某些情况下,zip()
可以用于矩阵转置等操作。例如,将多个行合并为列,或将多个列合并为行:
matrix = [(1, 2, 3), (4, 5, 6), (7, 8, 9)] transposed = zip(*matrix) print(list(transposed))
代码输出:
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
总结
到此这篇关于python中zip()函数用法及应用场景详解的文章就介绍到这了,更多相关python zip()函数详解内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论