博客
关于我
Python zip函数 详解(全)
阅读量:795 次
发布时间:2023-03-06

本文共 927 字,大约阅读时间需要 3 分钟。

Python zip函数详解

Python zip函数详解

1. zip函数简介

源码形式:zip([iterable, ...])

主要用途:将多个迭代器(如列表、元组、字典等)压缩为zip对象或列表形式,返回的元素为元组。不同版本的Python返回类型有所不同。

版本差异:

  • Python 3.x返回zip对象,主要减少内存占用。通过list(zip(...))可将结果转换为列表。
  • Python 2.x返回列表形式。

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/

你可能感兴趣的文章
oracle 创建字段自增长——两种实现方式汇总
查看>>
Oracle 升级10.2.0.5.4 OPatch 报错Patch 12419392 Optional component(s) missing 解决方法
查看>>
oracle 去重
查看>>
oracle 可传输的表空间:rman
查看>>
Oracle 启动监听命令
查看>>
Oracle 启动阶段 OPEN
查看>>
Oracle 在Drop表时的Cascade Constraints
查看>>
Oracle 在Sqlplus 执行sql脚本文件。
查看>>