本文共 927 字,大约阅读时间需要 3 分钟。
源码形式:zip([iterable, ...])
主要用途:将多个迭代器(如列表、元组、字典等)压缩为zip对象或列表形式,返回的元素为元组。不同版本的Python返回类型有所不同。
list(zip(...))
可将结果转换为列表。2. zip函数的实际应用
2.1 两列表的合并
list1 = [1,2,3]list2 = [4,5,6]
result = [x for x in zip(list1, list2)]print(result) # 输出: [(1,4), (2,5), (3,6)]
2.2 字典的压缩
dic1 = {1:2, 3:4, 5:6}result = [x for x in zip(dic1)]print(result) # 输出: [(1,), (3,), (5,)]
2.3 字符串的配对
char1 = "manong"char2 = "yanjiuseng"result = [x for x in zip(char1, char2)]print(result) # 输出: [('m','y'), ('a','a'), ('n','n'), ('o','j'), ('n','i'), ('g','u')]
2.4 超出常规用途——多维度数据处理
list1 = [1,2,3]list2 = [4,5,6]
unzipped = zip(*zip(list1, list2))list3, list4 = unzippedprint(list3) # 输出: (1,2,3)print(list4) # 输出: (4,5,6)
转载地址:http://tgafk.baihongyu.com/