栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 中的 zip() 函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python 中的 zip() 函数

zip() 函数 1. 功能

将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的 zip 对象。

2. 语法

zip(iterable)

参数说明:

  • iterables:可迭代对象,如列表、字典、元组、字符串等,zip() 函数允许多个可迭代对象作为参数。
  • 当 zip() 函数没有参数时,则返回空的迭代器。
  • 当 zip() 函数只有一个参数时,则从参数中依次取一个元素组成一个元组,再将依次组成的元组组合成一个新的迭代器。
  • 当 zip() 函数有两个参数时,分别从两个参数中依次各取出一个元素组成元组,再将依次组成的元组组合成一个新的迭代器。
  • 返回值:返回一个可迭代的 zip 对象,其内部元素为元组,可以使用 list() 函数或 tuple() 函数将其转换为列表或元组。
3. 示例 示例一:用 zip() 函数实现列表合并
name_list = ["kobe", "pual", "curry"]
num_list = [24, 3, 30]
print(list(zip(name_list, num_list)))

输出:

[('kobe', 24), ('pual', 3), ('curry', 30)]
示例二:使用 zip() 函数建立字典
name_list = ["kobe", "pual", "curry"]
team_list = ['lakers', 'worries', 'rockets']
print(dict(zip(name_list, team_list)))

输出:

{'kobe': 'lakers', 'pual': 'worries', 'curry': 'rockets'}
4. 解压——zip(*)

zip(*) 函数利用 * 号操作符,可以将元组解压为列表。

name_list = ["kobe", "pual", "curry"]
num_list = [24, 3, 30]

print(list(zip(name_list, num_list)))
print(list(zip(*zip(name_list, num_list))))

输出:

[('kobe', 24), ('pual', 3), ('curry', 30)]
[('kobe', 'pual', 'curry'), (24, 3, 30)]
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/341450.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号