You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

交换Python enumerate循环变量后触发AttributeError的原因解析

你的猜测完全正确!

先给你拆解清楚问题根源:

  • enumerate()遍历可迭代对象时,每次返回的是**(索引数字, 对应元素)**的固定顺序元组。
  • 正常代码里,你把变量按idx, char的顺序接收,char拿到的是字符串里的字符,调用char.isupper()完全合法,所以能正常运行。
  • 但交换变量顺序后,比如写成char, idx,这时候char实际接收到的是索引数字(int类型),你去调用int.isupper(),整数本身根本没有这个方法,自然就触发了AttributeError。

举个直观的代码对比:
正确写法:

def find_upper_indices(word):
    indices = []
    for idx, char in enumerate(word):
        if char.isupper():
            indices.append(idx)
    return indices

错误写法(交换变量顺序后):

def find_upper_indices(word):
    indices = []
    # 这里变量顺序搞反了,char拿到的是索引数字
    for char, idx in enumerate(word):
        if char.isupper():
            indices.append(idx)
    return indices

本质就是变量和enumerate()返回值的对应关系错了,你的判断完全准确。

内容的提问来源于stack exchange,提问作者portraitofperson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 19:50:20