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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)