Python enumerate 用法
2016-04-09 00:00
381 查看
摘要: 偶遇 enumerate 知晓它的奇妙之处
List 迭代时使用索引
使用索引,标准(一般)的做法
简单,干净的用法 ----使用enumerate
Return an enumerate object.
iterable must be a sequence, an iterator, or some other object which supports iteration
start:改变索引 初始化位置(以下有例子)
实例:
完整的用法:
有start 用法:
Equivalent to:
List 迭代时使用索引
使用索引,标准(一般)的做法
array = [1, 2, 3, 4, 5] for i in range(len(array)): print(array[i],end=' ')
1 2 3 4 5
简单,干净的用法 ----使用enumerate
enumerate(iterable, start=0)
Return an enumerate object.
iterable must be a sequence, an iterator, or some other object which supports iteration
start:改变索引 初始化位置(以下有例子)
实例:
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter'] >>> list(enumerate(seasons)) [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')] >>> list(enumerate(seasons, start=1)) [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
完整的用法:
array = [1, 2, 3, 4, 5] # or whatever for i, e in enumerate(array): print(i,e)
0 1 1 2 2 3 3 4 4 5
有start 用法:
for i, e in enumerate(array,start=2): print(i,e)
2 1 3 2 4 3 5 4 6 5
Equivalent to:
def enumerate(sequence, start=0): n = start for elem in sequence: yield n, elem n += 1
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法