about 3 years ago

Prefer enumerate Over range

flavor_list = ['vanilla', 'chocolate', 'pecan', 'strawberry']
for i in range(len(flavor_list)):
    flavor = flavor_list[i]
    print('%d: %s' % (i + 1, flavor))

上面的程式可以使用 enumerate()

for i, flavor in enumerate(flavor_list):
    print('%d: %s' % (i + 1, flavor))

enumerate() 可以傳入第二個參數

for i, flavor in enumerate(flavor_list, 1):
    print('%d: %s' % (i, flavor))

相關

Python 慣用語 - 6 善用 enumerate

← Effective Python 心得筆記: Item 9 Effective Python 心得筆記: Item 11 →
 
comments powered by Disqus