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

你可能感兴趣的文章
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>