1 # _*_ coding: utf-8 _*_ 2 # __Author: "LEMON" 3 4 5 list = [‘This‘, ‘is‘, ‘a‘, ‘test‘] 6 for i in range(len(list)): 7 print(i, list[i])
1 # _*_ coding: utf-8 _*_ 2 # __Author: "LEMON" 3 4 5 list = [‘This‘, ‘is‘, ‘a‘, ‘test‘] 6 #for i in range(len(list)): 7 # print(i, list[i]) 8 9 for index, item in enumerate(list): 10 print(index, item) 11 12 13 >>> 14 0 This 15 1 is 16 2 a 17 3 test
# _*_ coding: utf-8 _*_ # __Author: "LEMON" list = [‘This‘, ‘is‘, ‘a‘, ‘test‘] #for i in range(len(list)): # print(i, list[i]) #for index, item in enumerate(list): for index, item in enumerate(list,1): print(index, item) >>> 1 This 2 is 3 a 4 test
如果要统计文件的行数,可以这样写:
1 count = len(open(filepath, ‘r‘).readlines())
这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。
可以利用enumerate():
1 # _*_ coding: utf-8 _*_ 2 # __Author: "LEMON" 3 4 5 count = 0 6 for index, line in enumerate(open(‘test01.txt‘,‘r‘)): 7 count = count + 1 8 print(count)
1 # _*_ coding: utf-8 _*_ 2 # __Author: "LEMON" 3 4 5 week = [‘Mon‘, ‘Tue‘, ‘Wed‘, ‘Thu‘, ‘Fri‘] 6 weekend = [‘Sat‘, ‘Sun‘] 7 week.extend(weekend) 8 for i,j in enumerate(week,1): 9 print(i, j)
运行结果:
1 >>> 2 3 1 Mon 4 2 Tue 5 3 Wed 6 4 Thu 7 5 Fri 8 6 Sat 9 7 Sun
原文:http://www.cnblogs.com/lemonbit/p/6238402.html