其他语言中,比如C#,我们通常遍历数组是的方法是:
在Python中,我们习惯这样遍历:
这样遍历取不到item的序号i,所有就有了下面的遍历方法:
其实,如果你了解内置的enumerate函数,还可以这样写:
for
(
int
i
=
0
; i
<
list.Length; i
++
)
{
//todo with list[i]
}
{
//todo with list[i]
}
在Python中,我们习惯这样遍历:
for
item
in
sequence:
process(item)
process(item)
这样遍历取不到item的序号i,所有就有了下面的遍历方法:
for
index
in
range(len(sequence)):
process(sequence[index])
process(sequence[index])
其实,如果你了解内置的enumerate函数,还可以这样写:
for
index, item
in
enumerate(sequence):
process(index, item)
process(index, item)
Python 天天美味系列(总)
Python 天天美味(21) - httplib,smtplib
Python 天天美味(22) - 拷贝对象(深拷贝deepcopy与浅拷贝copy)
Python 天天美味(23) - enumerate遍历数组
...
本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/05/17/1201509.html,如需转载请自行联系原作者