python enumerate函数的使用方法总结

yipeiwu_com5年前Python基础

enumerate函数用于遍历序列中的元素以及它们的下标。

enumerate函数说明:

enumerate()是python的内置函数

enumerate在字典上是枚举、列举的意思

函数原型:enumerate(sequence, [start=0])

功能:将可循环序列sequence以start开始分别列出序列数据和数据下标

即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标。

举例说明:

存在一个sequence,对其使用enumerate将会得到如下结果:

start    sequence[0]
start+1  sequence[1]
start+2  sequence[2]......

适用版本:

  1. Python2.3+
  2. Python2.x

注意:在python2.6以后新增了start参数

英文解释:

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults to 0) and the values obtained from iterating over sequence。

代码实例:

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

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

输出为:

abcdefghij
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]

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

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

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'))

如果对一个列表,既要遍历索引又要遍历元素时,首先可以这样写:

list1 = ["这", "是", "一个", "测试"]
for i in range (len(list1)):
  print i ,list1[i]

上述方法有些累赘,利用enumerate()会更加直接和优美:

list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1):
  print index, item
>>>
0 这
1 是
2 一个
3 测试

enumerate还可以接收第二个参数,用于指定索引起始值,如:

list1 = ["这", "是", "一个", "测试"]
for index, item in enumerate(list1, 1):
  print index, item
>>>
1 这
2 是
3 一个
4 测试

补充

如果要统计文件的行数,可以这样写:

count = len(open(filepath, 'r').readlines())

这种方法简单,但是可能比较慢,当文件比较大时甚至不能工作。

可以利用enumerate():

count = 0
for index, line in enumerate(open(filepath,'r')): 
  count += 1

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python通过pil为png图片填充上背景颜色的方法

本文实例讲述了python通过pil为png图片填充上背景颜色的方法。分享给大家供大家参考。具体分析如下: png图片有些是没有背景颜色,如果希望以单色(比如白色)填充背景,可以使用下面...

python append、extend与insert的区别

最近在自学Python语言,看到向列表增加更多数据时被append(),extend(),insert()方法绕晕了。 append 和extend都只需要一个参数,并且自动添加到数组末...

对web.py设置favicon.ico的方法详解

本文介绍在web.py中设置favicon.ico的方法: 如果没设置favicon,后台日志是这样的: 127.0.0.1:4133 - - [03/Sep/2015 18:49:...

Python数据持久化存储实现方法分析

本文实例讲述了Python数据持久化存储实现方法。分享给大家供大家参考,具体如下: 1、pymongo的使用 前三步为创建对象 第一步创建连接对象 conn = pymong...

Python实现简单截取中文字符串的方法

本文实例讲述了Python实现简单截取中文字符串的方法。分享给大家供大家参考。具体如下: web应用难免会截取字符串的需求,Python中截取英文很容易: >>>...