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

本文共 938 字,大约阅读时间需要 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 = unzipped print(list3) # 输出: (1,2,3) print(list4) # 输出: (4,5,6)

转载地址:http://tgafk.baihongyu.com/

你可能感兴趣的文章
Numpy矩阵与通用函数
查看>>
numpy绘制热力图
查看>>
numpy转PIL 报错TypeError: Cannot handle this data type
查看>>
Numpy闯关100题,我闯了95关,你呢?
查看>>
nump模块
查看>>
Nutch + solr 这个配合不错哦
查看>>
NuttX 构建系统
查看>>
NutUI:京东风格的轻量级 Vue 组件库
查看>>