python之enumerate

enumerate参数为可遍历/可迭代的对象(如列表、字符串)
enumerate多用于在for循环中得到计数,利用它可以同时获得索引和值,即需要index和value值的时候可以使用enumerate
enumerate()返回的是一个enumerate对象

1.数组按照索引遍历

a=[1,2,3,4]
for i,j in enumerate(a):
    print ('{i},{j}'.format(i=i,j=j))

D:pythonpython.exe D:/pj/test/test.py
0,1
1,2
2,3
3,4

2.遍历索引指定2开始

a=[1,2,3,4]
for i,j in enumerate(a,2):
    print ('{i},{j}'.format(i=i,j=j))

D:pythonpython.exe D:/pj/test/test.py
2,1
3,2
4,3
5,4

3.统计文件行数(文件内容刚好4行)

count=0
for i,j in enumerate(open("1.txt",'r')):
    count+=1
print (count)

D:pythonpython.exe D:/pj/test/test.py
4

  

原文地址:https://www.cnblogs.com/letmeiscool/p/9708824.html