如何解决此代码中的错误?索引超出范围

时间:2020-05-04 22:42:24

标签: python

我有一个函数,可以让我输入任何字符串并按字母顺序返回高值。例如,如果我有一个类似“ Hello world”的句子,并且我们假设worldhello大,那么我们将返回world

此高值由我之前在string_index_in_char中设置的索引来衡量。

def func(string):
    char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    split_string = string.split()
    i = 0
    x = ""

    # get letters
    string = string.lower()
    for s in string:
        if s in char:
            string_index_in_char = char.index(s) + 1
        else:
            string_index_in_char = 0
        x += str(string_index_in_char)
        split_any_char_not_letters = x.split("0")
    # convert string into interger in list  
    for i in range(0, len(split_any_char_not_letters)): 
        split_any_char_not_letters[i] = int(split_any_char_not_letters[i])      
    convert_to_int = split_any_char_not_letters 

    # (split_string, convert_to_int) comparison
    n = convert_to_int.index(max(convert_to_int))
    my_string = split_string[n]
    print("%s -> %s" %(string, my_string.lower()))


#func("This Is my home")
func("Hello wOrld")

我收到此错误:

Traceback (most recent call last):
  File "D:\courses\udacity-python\python\Exam\alphabet\alphabet 5.py", line 27, in <module>
    func("This Is my home")
  File "D:\courses\udacity-python\python\Exam\alphabet\alphabet 5.py", line 23, in func
    my_string = split_string[n]
IndexError: list index out of range

仅当我输入诸如"man i need a taxi up to Ubud"之类的其他单词或某些单词时,我的问题才出现。那么,为什么在我输入“ hello world”时却没有向我发送此错误,却还是收到此错误?

1 个答案:

答案 0 :(得分:2)

已按照@Parakiwi的建议进行了更新:
当您分割zero时会发生问题,在您的示例中:这是我的家,t位于20位置,因为您被0分割后,会通过向代码添加额外的值来影响代码。拆分列表导致错误。更改为除<<carefully chosen split criteria>>这样的char索引之外的任意数字都可以:

更改:

if s in char:
    string_index_in_char = char.index(s) + 1
    print(string_index_in_char)
else:
    string_index_in_char = "^"
x += str(string_index_in_char)
split_any_char_not_letters = x.split("^")

之前:

if s in char:
            string_index_in_char = char.index(s) + 1
        else:
            string_index_in_char = 0
        x += str(string_index_in_char)
        split_any_char_not_letters = x.split("0")  

但是,您需要处理两个单词相等的情况。