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

Python运行报错AttributeError: 'list' object has no attribute 'find'如何解决

错误原因

AttributeError: 'list' object has no attribute 'find'报错的核心原因是:Python的列表(list)类型没有内置find()方法,find()是字符串专属的定位方法,列表查找元素对应索引要使用index()方法。

修复方案

有两种可直接落地的修改方式:

  • 方案1:保持现有列表逻辑,将find调用替换为列表的index方法
    将代码中loc = letters_list.find(char)修改为loc = letters_list.index(char)即可。如果输入内容包含非小写字母字符,可以额外加判断逻辑避免抛出ValueError。
  • 方案2:直接使用原始字符串调用find,无需转列表
    string.ascii_lowercase本身就是完整的小写字母字符串,不需要转成列表再操作,修改对应两行代码即可,兼容性更强,字符不存在时find会返回-1,不会直接抛出异常。

修复后完整代码示例(方案2)

import string

letters = string.ascii_lowercase
messages = input()
current_loc = -1
times = 0
if messages != 'halt':
    for char in messages:
        loc = letters.find(char)
        # 可选:加非小写字母兼容逻辑,比如遇到非小写字符跳过不计数
        # if loc == -1:
        #     continue
        if loc//3 == current_loc//3 or (loc//3 > 7 and current_loc//3 > 7):
            times += 2
        if loc % 3 == 0:
            times += 1
        elif loc % 3 == 1:
            times += 2
        else:
            times += 3
        current_loc = loc
    print(times)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 17:57:02