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 @   Hider1214  阅读(959)  评论(0编辑  收藏  举报
编辑推荐:
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
历史上的今天:
2018-06-01 MySQL学习笔记:like和regexp的区别
2018-06-01 MySQL学习笔记:regexp正则表达式
点击右上角即可分享
微信分享提示