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

Python中的enumerate()和zip()

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

Python中的enumerate()和zip()

enumerate()函数描述:

enumerate()函数:python内置函数

描述:enumerate()函数一般用于for循环中,可列出序列和下标位置对应的值。

语法:

enumerate(sequence, start])

参数:

  • sequence -- 一个序列、迭代器或其他支持迭代对象。

  • start -- 下标起始位置的值。

实例:for循环使用enumerate和普通for循环语法

#输出元祖,不加起始值,从0开始
list1= ['a','b','c','d','e']
for i in enumerate(list1):
    print(i)

out:
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')

#指定起始位置,从1开始
list1= ['a','b','c','d','e']
for i in enumerate(list1,1):
    print(i)
out:
(1, 'a')
(2, 'b')
(3, 'c')
(4, 'd')
(5, 'e')

列表转化为字典

list1= ['a','b','c','d','e']

#定义一个空字典,将列表list1转化为字典
list2 = {}
for i,value in enumerate(list1,1):
    list2[value]=i
print(list2)

out:
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

zip()将元祖,列表或者其他序列元素配对,构成由元祖构成的列表

#lis1和seq3元素个数相同时能完全匹配
list1= ['a','b','c','d','e']
seq3 = ['one','two','three','four','five']

ziped = zip(list1,seq3)
print(list(ziped))

out:
[('a', 'one'), ('b', 'two'), ('c', 'three'), ('d', 'four'), ('e', 'five')]

#lis1长度长于seq3
list1= ['a','b','c','d','e']
seq3 = ['one','two','three','four']

ziped = zip(list1,seq3)
print(list(ziped))
out:
[('a', 'one'), ('b', 'two'), ('c', 'three'), ('d', 'four')]

#seq3长于list1时:
list1= ['a','b','c','d','e']
seq3 = ['one','two','three','four','five','six','seven']
ziped = zip(list1,seq3)
print(list(ziped))
out:
[('a', 'one'), ('b', 'two'), ('c', 'three'), ('d', 'four'), ('e', 'five')]
#一般来书,enumerate和zip函数一起使用

list1= ['a','b','c','d','e']
seq3 = ['one','two','three','four','five',]
for i,(a,b) in enumerate(zip(list1,seq3)):
    print('{}:({},{})'.format(i,a,b))

out:
0:(a,one)
1:(b,two)
2:(c,three)
3:(d,four)
4:(e,five)

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829617.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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