Python 之实用函数enumerate()详解

enumerate() 是 Python 内置的一个实用函数,用于在遍历可迭代对象(如列表、元组、字符串等)时 同时获取元素的索引和值。它返回一个由 (索引, 值) 组成的元组序列,可显著简化需要索引的场景代码。

一、基本语法

enumerate(iterable, start=0)
  • iterable:要遍历的可迭代对象(如列表、字符串等)
  • start(可选):索引的起始值,默认从 0 开始

二、简单示例

fruits = ["apple", "banana", "cherry"]

# 遍历时获取索引和值
for index, value in enumerate(fruits):
    print(f"索引: {index}, 值: {value}")

# 输出:
# 索引: 0, 值: apple
# 索引: 1, 值: banana
# 索引: 2, 值: cherry

三、使用 start 参数 

# 让索引从 1 开始
for index, value in enumerate(fruits, start=1):
    print(f"位置: {index}, 水果: {value}")

# 输出:
# 位置: 1, 水果: apple
# 位置: 2, 水果: banana
# 位置: 3, 水果: cherry

四、常见应用场景

  1. 修改列表元素时跟踪位置

    numbers = [10, 20, 30, 40]
    for idx, num in enumerate(numbers):
        numbers[idx] = num * 2  # 原地修改元素
    print(numbers)  # 输出: [20, 40, 60, 80]
  2. 生成带索引的输出

    for i, char in enumerate("Python"):
        print(f"字符 '{char}' 的索引是 {i}")
  3. 构建索引到值的映射字典

    words = ["hello", "world", "python"]
    index_map = {idx: word for idx, word in enumerate(words)}
    print(index_map)  # 输出: {0: 'hello', 1: 'world', 2: 'python'}

五、对比传统写法(更简洁!)

假设不用 enumerate(),传统写法需要手动管理索引:

# 传统写法(冗长且容易出错)
fruits = ["apple", "banana", "cherry"]
index = 0
for fruit in fruits:
    print(f"索引: {index}, 值: {fruit}")
    index += 1

# 使用 enumerate() 更优雅
for index, fruit in enumerate(fruits):
    print(f"索引: {index}, 值: {fruit}")

六、注意事项

  • enumerate() 返回的是一个 迭代器对象,直接打印会显示内存地址,需遍历或转换为列表使用:
    print(enumerate(fruits))        # 输出: <enumerate object at 0x...>
    print(list(enumerate(fruits)))  # 输出: [(0, 'apple'), (1, 'banana'), (2, 'cherry')]
  • 如果只需要索引(不需要值),可以用 range(len(iterable)),但 enumerate 更 Pythonic。

七、总结

enumerate() 是 Python 中的高效工具,能简洁地处理需要同时操作索引和值的场景,避免手动维护计数器,使代码更清晰且易维护。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值