菜鸟笔记
提升您的技术认知

python中的enumerate函数介绍-ag真人游戏

enumerate英文翻译为枚举的意思。 可以将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。python 2.3. 以上版本可用,2.6 添加 start 参数。

  • 语法

>>> help(enumerate)
help on class enumerate in module __builtin__:
class enumerate(object)
 |  enumerate(iterable[, start]) -> iterator for index, value of iterable
 |
 |  return an enumerate object.  iterable must be another object that supports
 |  iteration.  the enumerate object yields pairs containing a count (from
 |  start, which defaults to zero) and a value yielded by the iterable argument.
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
  • 参数

  1. sequence       # 一个序列、迭代器或其他支持迭代对象。
  2. start                # 下标起始位置、默认为0
  • 返回值

返回枚举类型

>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>> list(enumerate(seasons))                # 默认start为0          
[(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
>>> list(enumerate(seasons, start=1))       # start为1
[(1, 'spring'), (2, 'summer'), (3, 'fall'), (4, 'winter')]
>>> s = "abcd"
>>> list(enumerate(s))                      # 字符串类型
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>> l = ["a", "b", "c", "d"]
>>> list(enumerate(l))                      # 列表类型
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>> t = ("a", "b", "c", "d")              
>>> list(enumerate(t))                      # 元祖类型                
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
>>> d = {"a": 1, "b": 2}
>>> list(enumerate(d))                      # 字典类型,枚举其key
[(0, 'a'), (1, 'b')]
>>>
  • 通过for循环遍历示例

>>> # 通过元素来遍历
>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>> count = 0
>>> for season in seasons:
...     print count,"=>", season
...     count  = 1
...
0 => spring
1 => summer
2 => fall
3 => winter
>>> # 通过索引来遍历
>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>> for i in range(len(seasons)):
...     print i, "=>", seasons[i]
...
0 => spring
1 => summer
2 => fall
3 => winter
>>>
  • 通过enumerate来遍历示例

>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>> for (index, season) in enumerate(seasons):
...     print index,"=>",season
...
0 => spring
1 => summer
2 => fall
3 => winter
>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>> for (index, season) in enumerate(seasons, start=1):
...     print index,"=>",season
...
1 => spring
2 => summer
3 => fall
4 => winter
>>>
  • 其它示例:统计文本的行数

通常的做法

>>> count = len(open(r"d:\\1.txt").readlines())
>>> count
7

 使用enumerate

>>> for index,line in enumerate(open(r"d:\\1.txt"), start=1):
...     pass
...
>>> index
7

 

网站地图