python3 enumetate 用法总结
enumerate用法总结-Python 3,enumerate-python
enumerate()说明
- enumerate()是python的内置函数
- enumerate在字典上是枚举、列举的意思
- 对于一个可迭代的(iterable)/可遍历的对象(如列表、字符串),enumerate将其组成一个索引序列,利用它可以同时获得索引和值
- enumerate多用于在for循环中得到计数
enumerate()使用
- 如果对一个列表,既要遍历索引又要遍历元素时,首先可以这样写:
# _*_ coding: utf-8 _*_
# __Author: "LEMON"
list = ['This', 'is', 'a', 'test']
for i in range(len(list)):
print(i, list[i])
- 上述方法有些累赘,利用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): print(index, item)
>>> This is 2 a 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():
# _*_ coding: utf-8 _*_ # __Author: "LEMON" count = 0 for index, line in enumerate(open('test01.txt','r')): count = count + 1 print(count)
examples:
# _*_ coding: utf-8 _*_
# __Author: "LEMON"
week = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
weekend = ['Sat', 'Sun']
week.extend(weekend)
for i,j in enumerate(week,1):
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

浙公网安备 33010602011771号