在Python中,for迴圈可用來遍訪字串、串列等iterator,若要計算迴圈的數量,可在迴圈
中用counter來記錄。
seq = ["one", "two", "three", "four", "five"]
counter = 0
for e in seq:
print (counter, e)
counter += 1
1 one
2 two
3 three
4 four
5 five
2 two
3 three
4 four
5 five
另外還有比較Pythonic的寫法,就是使用enumerate (sequence, [start=0]) 函數。
sequence代入iterator,start則為起始位置。
seq = ["one", "two", "three", "four", "five"]
for idx, e in enumerate(seq):
print (idx, e)
1 one
2 two
3 three
4 four
5 five
2 two
3 three
4 four
5 five
沒有留言:
張貼留言