码迷,mamicode.com
首页 > 编程语言 > 详细

Python内置函数enumerate()

时间:2017-06-18 14:16:58      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:art   iterator   reduce   位置   ret   uil   迭代   iterable   sign   

enumerate()是Python的内置函数。

 1 help(enumerate)
 2 Help on class enumerate in module builtins:
 3 class enumerate(object)
 4   enumerate(iterable[, start]) -> iterator for index, value of iterable
 5   #enumerate(可迭代变量[,开始下标])->返回迭代变量的索引和值。  (注意,字典和集合也能使用,取位置作为索引)
 6   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.
 7 enumerate is useful for obtaining an indexed list: 
 8       (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
 9  
10  Methods defined here:
11   
12 __getattribute__(self, name, /)
13       Return getattr(self, name).
14   
15 __iter__(self, /)
16       Implement iter(self).
17   
18 __new__(*args, **kwargs) from builtins.type
19      Create and return a new object.  See help(type) for accurate signature.
20 
21 __next__(self, /)
22      Implement next(self).
23  
24 __reduce__(...)
25     Return state information for pickling.

对于一个可迭代的iterable/可遍历的对象(如列表,字符串,元组,字典和集合)。

enumerate()多用于在for循环中得到计数;enumerate()返回的是一个enumerate对象。

 1 for i in enumerate([1,2,3,4,5]):  #对列表作用
 2     print(i)
 3     
 4 (0, 1)
 5 (1, 2)
 6 (2, 3)
 7 (3, 4)
 8 (4, 5)
 9 
10 for i in enumerate((1,2,3)): #对元组作用
11     print(i)
12     
13 (0, 1)
14 (1, 2)
15 (2, 3)
16 
17 for i in enumerate(help): #对字符串作用
18     print(i)
19     
20 (0, h)
21 (1, e)
22 (2, l)
23 (3, p)
24 
25 for i in enumerate({name:zoe,age:18}):  #对字典作用
26     print(i)
27     
28 (0, name)
29 (1, age)
30 
31 for i in enumerate({12,3}): #对元组作用
32     print(i)
33     
34 (0, 3)
35 (1, 12)

 

Python内置函数enumerate()

标签:art   iterator   reduce   位置   ret   uil   迭代   iterable   sign   

原文地址:http://www.cnblogs.com/zoe233/p/7043991.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!