Quantcast
Channel: CodeSection,代码区,Python开发技术文章_教程 - CodeSec
Viewing all articles
Browse latest Browse all 9596

enumerate用法总结-Python 3

$
0
0
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


Viewing all articles
Browse latest Browse all 9596

Trending Articles