首页 > 编程语言 > 详细

python之enumerate

时间:2018-09-26 18:58:47      阅读:229      评论:0      收藏:0      [点我收藏+]

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:\python\python.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:\python\python.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:\python\python.exe D:/pj/test/test.py
4

  

 

python之enumerate

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!