Python学习笔记:enumerate枚举函数

一、介绍

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

枚举、列举的意思,返回一个 enumerate 对象。

二、语法

enumerate(sequence, [start = 0])
  • sequence 一个序列、迭代器或其他支持迭代对象
  • start 下标开始位置

返回 enumerate(枚举)对象。

三、实例

实例1:

seasons = ['Spring', 'Summer', 'Fall', 'Winter']

# 返回内存地址
enumerate(seasons) # <enumerate at 0xae1b6c0>

# 从0开始
list(enumerate(seasons)) # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

# 从下标1开始 还是返回4个值
list(enumerate(seasons, start = 1)) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

普通的 for 循环:

i = 0
seq = ['one', 'two', 'three']

for element in seq:
    print(i, seq[i])
    i += 1

# output
0 one
1 two
2 three 

for 循环使用enumerate:

seq = ['one', 'two', 'three']

for i, element in enumerate(seq):
    print(i, seq[i])

# output
0 one
1 two
2 three  

实例2:

lst = [1,2,3,4,5,6]
for index, value in enumerate(lst):
    print('%s, %s' % (index, value))

# output
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6

# 指定索引从1开始
lst = [1,2,3,4,5,6]
for index, value in enumerate(lst, start = 1):
    print('%s, %s' % (index, value))

# output
1, 1
2, 2
3, 3
4, 4
5, 5
6, 6

参考链接1:Python enumerate() 函数

参考链接2:Python中enumerate用法详解

posted @ 2020-06-01 00:13  Hider1214  阅读(870)  评论(0编辑  收藏  举报