python学习随笔之enumerate

说明

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。

Python 2.3. 以上版本可用,2.6 添加 start 参数。

语法

以下是 enumerate() 方法的语法:

1 enumerate(sequence, [start=0])

参数

  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置。

返回值

返回 enumerate(枚举) 对象。

实验验证:

1 seasons = ['Spring', 'Summer', 'Fall', 'Winter']
2 list1 = list(enumerate(seasons))
3 print(list1)
4 list2 = list(enumerate(seasons, start=1))       # 下标从 1 开始
5 print(list2)

jupyter notebook 实验结果:

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

 

posted @ 2021-03-03 15:55  飞猪流  阅读(73)  评论(0)    收藏  举报