首页 > 解决方案 > AttributeError:“列表”对象没有属性“查找”

问题描述

以下代码导致 AttributeError: 'list' object has no attribute 'find' 我不知道如何修复它:

    import string

    letters_list = list(string.ascii_lowercase)
    messages = input()
    current_loc = -1
    times = 0
    if messages != 'halt':
        for char in messages:
            loc = letters_list.find(char)
            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)

标签: python-3.x

解决方案


不确定您对输出的期望。但不是find,而是尝试使用index来获取字符的索引。

import string

letters_list = list(string.ascii_lowercase)
messages = input()
current_loc = -1
times = 0
if messages != 'halt':
    for char in messages:
        loc = letters_list.index(char)
        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)

推荐阅读