介绍
enumerate() 函数用于将一个可遍历的数据对象 (如列表, 元组或字符串) 组合为一个索引序列, 同时列出数据和数据下标, 一般用在 for 循环当中
- s1 = 'Hello'
- for i, j in enumerate(s1):
- print(i, j)
- """
- 0 H
- 1 e
- 2 l
- 3 l
- 4 o
- """li = ['apple','mi','mac','linux']
- for index, j in enumerate(li):
- print(index, j)
- """
- 0 apple
- 1 mi
- 2 mac
- 3 linux
- """li = ('book','pen','mac','suf')
- for index, j in enumerate(li):
- print(index, j)
- """
- 0 book
- 1 pen
- 2 mac
- 3 suf
- """
可以使用 start 参数
- li = ('book', 'pen', 'mac', 'suf')
- for index, j in enumerate(li, start=1):
- print(index, j)
- """
- 1 book
- 2 pen
- 3 mac
- 4 suf
- """
来源: http://www.bubuko.com/infodetail-3090518.html