enumerate()是Python的內(nèi)置函數(shù)。
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(可迭代變量[,開始下標(biāo)])->返回迭代變量的索引和值。 (注意,字典和集合也能使用,取位置作為索引) 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.type19 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循環(huán)中得到計(jì)數(shù);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)
聯(lián)系客服