天天看點

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,如需轉載請自行聯系原作者