首页Python【Python内置函数】e...

【Python内置函数】enumerate()函数

Python 提供了许多内置函数,这些函数是Python语言的一部分,可以直接在Python程序中使用而无需导入任何模块。

本系列将会陆续整理分享一些的Python内置函数。

文章配套代码获取有以下两种途径:
  • 通过百度网盘获取:
链接:https://pan.baidu.com/s/11x9_wCZ3yiYOe5nVcRk2CQ?pwd=mnsj 提取码:mnsj
  • 前往GitHub获取
https://github.com/returu/Python_built-in_functions





01
简介

enumerate() 函数是 Python 中的一个内置函数,用于将一个可迭代的数据对象(如列表、元组或字符串)组合为一个索引序列,包括数据和数据索引。

enumerate() 函数的基本语法如下:

enumerate(iterable, start=0)
参数说明:
  • iterable:一个可迭代对象,比如列表、元组或字符串;
  • start:一个可选参数,用于指定计数的起始值,默认为0。

返回值:

enumerate() 函数返回一个枚举对象,该对象可以被用来创建一个索引序列。这个枚举对象是可迭代的,每次迭代都会返回一个元组,其中包含当前的索引(从 start 开始)和对应的元素。即,enumerate() 返回的迭代器的 __next__() 方法会返回一个元组,其中包含一个计数和在 iterable 上迭代得到的值。

等同于下面自定义的enumerate函数,其内部使用一个循环遍历iterable中的每个元素,并使用 yield 语句返回一个包含当前索引(从 start 开始)和元素的元组,每次循环迭代,索引 n 都会递增1。


def enumerate(iterable, start=0):
    n = start
    for elem in iterable:
        yield n, elem
        n += 1


02
使用

下面是一些使用 enumerate() 函数的示例:

  • 示例 1:基本使用


fruits = ['apple''banana''cherry']

enumerate(fruits)
# 输出:<enumerate at 0x20d25873c90>

list(enumerate(fruits))
# 输出:[(0, 'apple'), (1, 'banana'), (2, 'cherry')]

for index, fruit in enumerate(fruits):
    print(f"Index: {index}, Fruit: {fruit}")
# 输出:Index: 0, Fruit: apple
#      Index: 1, Fruit: banana
#      Index: 2, Fruit: cherry


  • 示例 2:指定起始索引(start参数)


fruits = ['apple''banana''cherry']
for index, fruit in enumerate(fruits, start=1):
    print(f"Index: {index}, Fruit: {fruit}")
# 输出:Index: 1, Fruit: apple
#      Index: 2, Fruit: banana
#      Index: 3, Fruit: cherry


  • 示例 3:在字符串上使用


for index, char in enumerate("hello"):
    print(f"Index: {index}, Character: {char}")
# 输出:Index: 0, Character: h
#      Index: 1, Character: e
#      Index: 2, Character: l
#      Index: 3, Character: l
#      Index: 4, Character: o

本篇文章来源于微信公众号: 码农设计师

RELATED ARTICLES

欢迎留下您的宝贵建议

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments