跟老齐学Python之关于循环的小伎俩(3)
>>> mylist = ["qiwsir",703,"python"]
>>> new_list = []
>>> for i in range(len(mylist)):
... new_list.append((i,mylist[i]))
...
>>> new_list
[(0, 'qiwsir'), (1, 703), (2, 'python')]
enumerate的作用就是简化上述操作:
>>> enumerate(mylist)
<enumerate object at 0xb74a63c4> #出现这个结果,用list就能显示内容.类似的会在后面课程出现,意味着可迭代。
>>> list(enumerate(mylist))
[(0, 'qiwsir'), (1, 703), (2, 'python')]
对enumerate()的深刻阐述,还得看这个官方文档:
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 =
T.new(S, ...) -> a new object with type S, a subtype of T
对官方文档,有的朋友可能看起来有点迷糊,不要紧,至少浏览一下,看个大概。因为随着个人实践的越来越多,对文档的含义理解会越来越深刻。这就好比令狐冲,刚刚学习了独孤九剑的口诀和招式后,理解不是很深刻,只有在不断的打打杀杀实践中,特别跟东方不败等高手过招之后,才能越来越体会到独孤九剑中的奥妙。






