Python enumerate 学习


在for循环中得到计数

参数为可遍历的变量,如:字符串,列表等;返回值为enumerate类

import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)

输出为:

abcdefghijklmnopqrstuvwxyz
[(0, ‘a’), (1, ‘b’), (2, ‘c’), (3, ‘d’), (4, ‘e’), (5, ‘f’), (6, ‘g’), (7, ‘h’), (8, ‘i’), (9, ‘j’)……(25, ‘z’)]

在同时需要index和value值的时候可以使用 enumerate

enumerate 实战

line 是个 string ,包含 0 和 1,要把1都找出来:

#方法一
def read_line(line):
    sample = {}
    n = len(line)
    for i in range(n):
        if line[i]!='0':
            sample[i] = int(line[i])
    return sample
#方法二
def xread_line(line):
    return((idx,int(val)) for idx, val in enumerate(line) if val != '0')
print read_line('0001110101')
print list(xread_line('0001110101'))

一般情况下对一个列表或数组既要遍历索引又要遍历元素时,会这样写:

for i in range(0, len(list)):
    print i ,list[i]

但是这种方法有些累赘,使用内置enumerrate函数会有更加直接,优美的做法,先看看enumerate的定义:

def enumerate(collection):
    'Generates an indexed series:  (0,coll[0]), (1,coll[1]) ...'
    i = 0
    it = iter(collection)
    while 1:
        yield(i, it.next())
    i += 1

enumerate会将数组或列表组成一个索引序列。使我们再获取索引和索引内容的时候更加方便如下:

for index,text in enumerate(list)):
    print index ,text

在cookbook里介绍,如果你要计算文件的行数,可以这样写:

count = len(open(thefilepath,‘rU’).readlines())

前面这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作,下面这种循环读取的方法更合适些:

Count = -1
for count,line in enumerate(open(thefilepath,'rU')):
    pass
Count += 1

还有一种计算文件行数的方法:

def linecount(filename):
    '''返回文件的行数'''
    fp = open(filename)
    lc = sum(1 for line in fp)
    fp.close()
    return lc

-EOF-


发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注