enumerate()說明
- enumerate()是python的內置函數
- enumerate在字典上是枚舉、列舉的意思
- 對於一個可迭代的(iterable)/可遍歷的對象(如列表、字符串),enumerate將其組成一個索引序列,利用它可以同時獲得索引和值
- enumerate多用於在for循環中得到計數
enumerate()使用
- 如果對一個列表,既要遍歷索引又要遍歷元素時,首先可以這樣寫:
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])
- 上述方法有些累贅,利用enumerate()會更加直接和優美:
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
- enumerate還可以接收第二個參數,用於指定索引起始值,如:
# _*_ 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)
examples:
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