python中的enumerate()函数使用方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_20183817/article/details/82180815

结合实例来理解比较好,网上找了一下这个enumerate用法,自己也记录一下加深印象

  • enumerate函数说明:
    • 函数原型:enumerate(sequence, [start=0])  #第二个参数为指定索引
    • 功能:将可循环序列sequence以start开始分别列出序列数据和数据下标
    • 即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标
  • 举例说明:
    • 存在一个sequence,对其使用enumerate将会得到如下结果:
      • start        sequence[0]
      • start+1  sequence[1]
      • start+2    sequence[2]......
  • 具体例子:

打印输出索引与value值 

#列表1
print '列表1'
product = ["Mac pro", "iPhone", "iWatch"]
for index, item in enumerate(product):
    print(index, item)
    
#列表2
print '列表2'
list = [1, 2, 3, 4, 5, 6]
print list[::-1] #倒叙排列
for index, item in enumerate(list):
    print(index, item)

#字符串
print '字符串'
for i, j in enumerate('abcde'):
    print(i, j)
    
#数组
print '数组'
for i, j in enumerate(('a', 'b', 'c', 'd', 'e')):
    print(i, j)

#字典
print '字典'
for i, j in enumerate({'a':1, 'b':2}):
    print (i, j)
#输出结果
列表1
(0, 'Mac pro')
(1, 'iPhone')
(2, 'iWatch')
列表2
[6, 5, 4, 3, 2, 1]
(0, 1)
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, 6)
字符串
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
数组
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
字典
(0, 'a')
(1, 'b')
>>> product = [
...         "Mac pro",
...         "iPhone",
...         "iWatch"
...     ]
>>> for index,item in enumerate(product):
…          print(index,item)
>>>

#得到以下结果 
0     Mac pro
1    iPhone
2    iWatch
#也可以使用enumerate函数的第二个参数:
>>> for index,item in enumerate(product,1)://第二个参数表示下标开始的位置,取值为1即表示下标从1开始计算,默认从0开始
 …          print(index,item)
>>>
#得到以下结果
1  Mac pro
2   iPhone
3   iWatch
# 列表里包含元组
regs = [
    ('D', 1),
    ('R', 2),
    ('B', 3),
    ('Ba', 4)]
print regs
print type(regs[0])
print regs[0][0]
print regs[0][1]
print type(regs[0][1])
print type(regs[0][0])

返回结果: 

[('D', 1), ('R', 2), ('B', 3), ('Ba', 4)]
<type 'tuple'>
D
1
<type 'int'>
<type 'str'>

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/baidu_20183817/article/details/82180815