在使用Python的for loop去iterate一個list時,最直覺想到的方法如下

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
count = 0
for i in choices:
    print count,i
    count += 1

 

但是呢,Python裡面有個好用的built-in function叫做enumerate

所以其實是不用這麼麻煩的啦~

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices):
    print index, item

輸出結果為

Your choices are:

0 pizza

1 pasta

2 salad

3 nachos

但是,如果今天我們想讓第一個index為1,輸出1 2 3 4,又該怎麼做呢

這一切enumerate()也幫我們想好了

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices, start = 1):
    print index, item

輸出結果為

Your choices are:

1 pizza

2 pasta

3 salad

4 nachos

只要設定start = 1就行囉

雖然是很基本的function,可是很好用,所以記錄下來

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 wrijLove 的頭像
    wrijLove

    宅宅情侶的成長日記

    wrijLove 發表在 痞客邦 留言(0) 人氣()