博客
关于我
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 11g关闭用户连接审计
查看>>
Oracle 11g忘记sys、system、scott密码该这样修改!
查看>>
Oracle 11g数据库安装和卸载教程
查看>>
Oracle 11g数据库成功安装创建详细步骤
查看>>
Oracle 11g超详细安装步骤
查看>>
Oracle 12c中的MGMTDB
查看>>
Oracle 12c安装报错Installation failed to access the temporary location(无法访问临时位置)...
查看>>
Oracle 9i数据库管理教程
查看>>
ORACLE Active dataguard 一个latch: row cache objects BUG
查看>>
oracle avg、count、max、min、sum、having、any、all、nvl的用法
查看>>
Oracle BEQ方式连接配置
查看>>
oracle Blob保存方式,oracle 存储过程操作blob
查看>>
Oracle BMW Racing sailing vessel帆船图
查看>>
ORACLE Bug 4431215 引发的血案—原因分析篇
查看>>
Oracle Business Intelligence Downloads
查看>>
Oracle cmd乱码
查看>>
Oracle Corp甲骨文公司推出Oracle NoSQL数据库2.0版
查看>>
uniapp超全user-agent判断 包括微信开发工具 hbuilder mac windows 安卓ios端及本地识别
查看>>
Oracle DBA课程系列笔记(20)
查看>>
oracle dblink 创建使用 垮库转移数据
查看>>