|
在python中使用enumerate() function.
在对列表遍历的时候.我是使用 for 进行遍历,今天发现enumerate 可以在同时需要index和value的时候用
- >>> name
- ['ca', 'tom', 'lili', 'sunwukong']
- >>> for i in range(len(name)):
- ... print i,name
- ...
- 0 ca
- 1 tom
- 2 lili
- 3 sunwukong
使用enumerate() function 可以更效率,更方便一些
- >>> for i,eachname in enumerate(name):
- ... print "%d %s" %(i,eachname)
- ...
- 0 ca
- 1 tom
- 2 lili
- 3 sunwukong
以下摘在python help
- 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]), ...
- |
- | Methods defined here:
- |
- | __getattribute__(...)
- | x.__getattribute__('name') <==> x.name
- |
- | __iter__(...)
- | x.__iter__() <==> iter(x)
- |
- | next(...)
- | x.next() -> the next value, or raise StopIteration
- |
- | ----------------------------------------------------------------------
- | Data and other attributes defined here:
- |
- | __new__ = <built-in method __new__ of type object>
- | T.__new__(S, ...) -> a new object with type S, a subtype of T
|
|
|