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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值