python每天一个技巧——Day 3 | 使用 enumerate 获取索引和值

今天我们专注学习 Day 3:使用 enumerate 获取索引和值。这是处理序列时极其重大的技巧。

深度解析:enumerate()函数

1. 为什么要使用enumerate()?

传统方法的问题

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

# ❌ 不推荐的做法
for i in range(len(fruits)):
    print(f"索引: {i}, 值: {fruits[i]}")

问题:

  • 代码冗长
  • 需要多次访问列表(fruits[i])
  • 可读性差

2. 基础用法

enumerate() 返回一个包含索引和值的元组序列:

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

# ✅ 推荐的做法
for index, fruit in enumerate(fruits):
    print(f"索引: {index}, 水果: {fruit}")

输出:

索引: 0, 水果: apple
索引: 1, 水果: banana
索引: 2, 水果: cherry

3.start参数:自定义起始索引

默认从 0 开始,但可以自定义:

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

# 从 1 开始计数(适合给人看的编号)
for number, fruit in enumerate(fruits, start=1):
    print(f"第{number}个水果: {fruit}")

输出:

第1个水果: apple
第2个水果: banana
第3个水果: cherry

4. 实际应用场景

场景1:处理列表时需要索引

# 标记重大任务
tasks = ['写报告', '开会', '写代码', '测试']
important_indices = []

for idx, task in enumerate(tasks):
    if '写' in task:
        important_indices.append((idx, task))

print("需要重点关注的任务:", important_indices)
# 输出: [(0, '写报告'), (2, '写代码')]

场景2:创建字典映射

# 将列表元素映射到它们的索引
students = ['Alice', 'Bob', 'Charlie']
student_dict = {student: idx for idx, student in enumerate(students)}
print(student_dict)  # 输出: {'Alice': 0, 'Bob': 1, 'Charlie': 2}

场景3:处理文件内容

# 模拟文件行内容
file_lines = ["# 标题1", "内容1", "# 标题2", "内容2"]

print("文件结构分析:")
for line_num, line in enumerate(file_lines, start=1):
    if line.startswith('#'):
        print(f"第{line_num}行是标题: {line[2:]}")

5. 与列表推导式结合

numbers = [10, 20, 30, 40, 50]

# 为每个数字添加索引
indexed_numbers = [(idx, num) for idx, num in enumerate(numbers)]
print(indexed_numbers)  # 输出: [(0, 10), (1, 20), (2, 30), (3, 40), (4, 50)]

# 只保留偶数索引的元素
even_index_items = [num for idx, num in enumerate(numbers) if idx % 2 == 0]
print(even_index_items)  # 输出: [10, 30, 50]

6. 高级用法技巧

技巧1:直接转换为列表

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

技巧2:多个列表同时枚举

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 92, 78]

for idx, (name, score) in enumerate(zip(names, scores)):
    print(f"学生{idx}: {name} -> {score}分")

技巧3:寻找特定元素

def find_index(items, target):
    """返回元素的第一个出现位置"""
    for idx, item in enumerate(items):
        if item == target:
            return idx
    return -1

data = ['a', 'b', 'c', 'b', 'a']
print(find_index(data, 'b'))  # 输出: 1
print(find_index(data, 'x'))  # 输出: -1

7. 性能优势

enumerate() 比传统方法更高效:

  • 直接生成(索引, 值)对
  • 避免重复的列表索引访问
  • 内存友善(惰性求值)

8. 实际项目案例

案例1:简单的待办事项管理器

class TodoList:
    def __init__(self):
        self.tasks = []
    
    def add_task(self, task):
        self.tasks.append(task)
    
    def show_tasks(self):
        if not self.tasks:
            print("没有待办事项!")
            return
        
        print("你的待办事项:")
        for idx, task in enumerate(self.tasks, start=1):
            print(f"{idx}. {task}")
    
    def remove_task(self, task_number):
        if 1 <= task_number <= len(self.tasks):
            removed = self.tasks.pop(task_number - 1)
            return f"已删除: {removed}"
        return "无效的编号"

# 使用示例
todo = TodoList()
todo.add_task("学习Python")
todo.add_task("写作业")
todo.add_task("锻炼")
todo.show_tasks()

案例2:数据分析辅助

def analyze_data(data):
    """分析数据并返回统计信息"""
    results = {
        'positive': [],
        'negative': [],
        'zero': []
    }
    
    for idx, value in enumerate(data):
        if value > 0:
            results['positive'].append((idx, value))
        elif value < 0:
            results['negative'].append((idx, value))
        else:
            results['zero'].append((idx, value))
    
    return results

# 测试
data = [1, -2, 0, 3, -1, 0, 4]
analysis = analyze_data(data)
print("正数位置:", analysis['positive'])
print("负数位置:", analysis['negative'])
print("零值位置:", analysis['zero'])

今日练习

练习1:基础应用

colors = ['red', 'green', 'blue', 'yellow', 'purple']
# 使用 enumerate 打印每个颜色及其编号(从1开始)
# 你的代码 here

练习2:实用函数

def find_all_occurrences(items, target):
    """
    返回目标值在列表中的所有出现位置
    示例: find_all_occurrences([1, 2, 3, 2, 4, 2], 2) -> [1, 3, 5]
    """
    # 你的代码 here
    pass

# 测试
numbers = [1, 2, 3, 2, 4, 2, 5]
print(find_all_occurrences(numbers, 2))

练习3:实战应用

def format_menu(options):
    """
    将选项列表格式化为带编号的菜单字符串
    示例: ['新建', '打开', '保存'] -> "1. 新建
2. 打开
3. 保存"
    """
    # 你的代码 here
    pass

# 测试
menu_options = ['新建文件', '打开文件', '保存文件', '退出']
print(format_menu(menu_options))

练习答案:

# 练习1答案:
for num, color in enumerate(colors, start=1):
    print(f"{num}. {color}")

# 练习2答案:
def find_all_occurrences(items, target):
    return [idx for idx, item in enumerate(items) if item == target]

# 练习3答案:
def format_menu(options):
    return "
".join([f"{idx}. {option}" for idx, option in enumerate(options, start=1)])

今日总结

  • enumerate(iterable, start=0) 同时获取索引和值
  • 使用 start 参数 来自定义起始编号
  • 比 range(len()) 更优雅高效
  • 适用于各种需要索引的场景

记住这个简单的规则:当你需要索引时,就用 enumerate()

明天我们将学习另一个强劲的迭代工具:zip() 函数的使用技巧。

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
Villain_0522的头像 - 鹿快
评论 共1条

请登录后发表评论