python:遍歷相關tips

enumerate

使用場景
遍歷可迭代對象時,想同時輸出元素的索引和值。
替代for i in range(len(ys))這種笨重的寫法。

接口

Init signature: enumerate(iterable, start=0)
Docstring:     
Return an enumerate object.

  iterable
    an object supporting 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]), ...

實例

In [7]: a = ['a', 'b', 'c']

In [8]: for i in enumerate(a):
   ...:     print(i)
   ...: 
(0, 'a')
(1, 'b')
(2, 'c')

In [9]: for i,v in enumerate(a):
   ...:     print(i,v)
   ...: 
0 a
1 b
2 c

未完待續…

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章