博客
关于我
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/

你可能感兴趣的文章
numpy、cv2等操作图片基本操作
查看>>
numpy中的argsort的用法
查看>>
NumPy中的精度:比较数字时的问题
查看>>
numpy判断对应位置是否相等,all、any的使用
查看>>
Numpy多项式.Polynomial.fit()给出的系数与多项式.Polyfit()不同
查看>>
Numpy如何使用np.umprod重写range函数中i的python
查看>>
numpy学习笔记3-array切片
查看>>
numpy数组替换其中的值(如1替换为255)
查看>>
numpy数组索引-ChatGPT4o作答
查看>>
numpy最大值和最大值索引
查看>>
NUMPY矢量化np.prod不能构造具有超过32个操作数的ufunc
查看>>
Numpy矩阵与通用函数
查看>>
numpy绘制热力图
查看>>
numpy转PIL 报错TypeError: Cannot handle this data type
查看>>
Numpy闯关100题,我闯了95关,你呢?
查看>>
nump模块
查看>>
Nutch + solr 这个配合不错哦
查看>>
NuttX 构建系统
查看>>
NutUI:京东风格的轻量级 Vue 组件库
查看>>
NutzCodeInsight 2.0.7 发布,为 nutz-sqltpl 提供友好的 ide 支持
查看>>