1. 程式人生 > >Python內置函數enumerate()

Python內置函數enumerate()

list tor supports 對象 nature start star bject use

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