Python 中enumerate的使用
2016-04-13 22:30
375 查看
在索引迭代序列中我们可以通过range()和len()函数遍历序列中的元素以及元素的下标:
然而大部分情况下我们可以使用enumerate函数进行相同的操作:
enumerate函数用于遍历序列中的元素以及它们的下标:
同时,
>>> a = ['Mary','had','a','littel','lamb'] >>> for i in range(len(a)): print(i,a[i]) 0 Mary 1 had 2 a 3 littel 4 lamb
然而大部分情况下我们可以使用enumerate函数进行相同的操作:
enumerate函数用于遍历序列中的元素以及它们的下标:
>>> for i,j in enumerate(('a','b','c')):#遍历tuple,注意:两层括号 print(i,j) 0 a 1 b 2 c >>> for i,j in enumerate([1,2,3]):#遍历list print(i,j) 0 1 1 2 2 3 >>> for i ,j in enumerate({'a':1,'b':2,'c':3}):#遍历dic print(i,j) 0 a 1 b 2 c >>> for i,j in enumerate('abc'):#遍历字符串 print(i,j) 0 a 1 b 2 c
同时,
enumerate本身是一个生成器函数,可以如下方式使用:
#本身是生成器 In [19]: enumerate('abcdef', 1) Out[19]: <enumerate at 0xa027360> #生成带有索引的元组的列表(一组记录) In [20]: list(enumerate('abcdef', 1)) Out[20]: [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e'), (6, 'f')] #指定起始索引 In [21]: list(enumerate('abcdef', 10)) Out[21]: [(10, 'a'), (11, 'b'), (12, 'c'), (13, 'd'), (14, 'e'), (15, 'f')] #与itertools联用,有特效 In [22]: from itertools import chain In [23]: list(chain(enumerate('abcdef', 10))) Out[23]: [(10, 'a'), (11, 'b'), (12, 'c'), (13, 'd'), (14, 'e'), (15, 'f')] #将索引与记录合并 In [24]: list(chain.from_iterable(enumerate('abcdef', 10))) Out[24]: [10, 'a', 11, 'b', 12, 'c', 13, 'd', 14, 'e', 15, 'f']
相关文章推荐
- Python你必须知道的十个库
- Python轻量级库web.py
- python 简单爬虫原理
- Python装饰器
- 数字:
- pyspark使用 jupyter ,matplotlib, ipython
- 初识Python
- ubuntu安装pip+python27+ipython+scrapy+zlib-及遇到的各种问题解决
- ubuntu-pip+python27+ipython-安装-及遇到的各种问题解决
- python基本数据类型-字典
- sublime 安装Python
- python基本数据类型-元组
- Python3爬虫实战:爬取大众点评网某地区所有酒店相关信息
- python的函数
- 使用2to3将代码移植到Python 3
- Python模块受欢迎排行榜Top200
- python文件操作
- Windows下Python包的pip安装
- [转]关于Sublime的repl设置
- python 日志