天天看点

Python天天美味(23) - enumerate遍历数组

其他语言中,比如C#,我们通常遍历数组是的方法是:

Python天天美味(23) - enumerate遍历数组

for (int i = 0; i < list.Length; i++)

Python天天美味(23) - enumerate遍历数组

{

Python天天美味(23) - enumerate遍历数组

    //todo with list[i]

Python天天美味(23) - enumerate遍历数组

}

在Python中,我们习惯这样遍历:

Python天天美味(23) - enumerate遍历数组

for item in sequence:

Python天天美味(23) - enumerate遍历数组

    process(item)

这样遍历取不到item的序号i,所有就有了下面的遍历方法:

Python天天美味(23) - enumerate遍历数组

for index in range(len(sequence)):

Python天天美味(23) - enumerate遍历数组

    process(sequence[index])

其实,如果你了解内置的enumerate函数,还可以这样写:

Python天天美味(23) - enumerate遍历数组

for index, item in enumerate(sequence):

Python天天美味(23) - enumerate遍历数组

    process(index, item)

<a target="_blank" href="http://www.cnblogs.com/coderzh/archive/2008/05/17/1201509.html">Python 天天美味(23) - enumerate遍历数组</a>

...

本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/05/17/1201509.html,如需转载请自行联系原作者