介绍
enumerate()是python的内置函数。对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate()将其组成一个索引序列,利用它可以同时获得索引和值。这个函数多用于在for循环中得到计数。
my_list = ['apple','banana','grapes','pear']
for c, value in enumerate(my_list, 1):
print(c,value)
#output:
#1 apple
#2 banana
#3 grapes
#4 pear
上述代码说明enumerate()可以接受第二个参数,用于指定索引起始值。
比较
对于一个列表,既要遍历索引又要遍历元素时,首先可以这样写:
my_list = ['apple','banana','grapes','pear']
for i in range(len(my_list)):
print i, my_list[i]
上述方法有些累赘,利用enumerate()会更加直接:
my_list = ['apple','banana','grapes','pear']
for index, item in enumerate(my_list):
print index, item
#output:
#0 apple
#1 banana
#2 grapes
#3 pear
补充
如果要统计文件的行数,可以这样写:
count = len(open(filepath,'r').readlines())
这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。
可以利用enumerate():
count = 0
for index, line in enumerate(open(filepath,'r'):
count += 1