1、一般要同時遍歷數組的索引和元素需要先確定數組的長度length(元素個數),然后使用range函數來生成數組的索引,最后使用該索引來訪問數組的元素。
具體做法如下:
l = [2,7,11,15] for i in range(len(l)): print i,l[i]
結果:
0 2 1 7 2 11 3 15
2、使用enumerate函數可以很方便的做到以上功能
l = [2,7,11,15] for index,value in enumerate(l): print index,value
結果:
0 2 1 7 2 11 3 15