首页 > 解决方案 > 猪拉丁函数代码列表中的值错误。当 x 明显在列表中时,删除(x)x 不在列表中

问题描述

编写一个接收文本并返回猪拉丁语翻译的猪拉丁文函数。试图删除前辅音,但得到 List.remove(x) x 不在列表中的 ValueError。打印语句表明这是不正确的。

当输入是单个单词与包含多个单词的文本时,我编写了一个类似的程序。该程序在一个单词输入下运行良好,但是当我尝试修改多个单词输入时。

我尝试复制我要修改的单词,以防删除字母会弄乱迭代。这似乎没有帮助,我在尝试删除字母时仍然遇到同样的错误。


def is_consonant(character):

    """takes a character and returns True if it is a consonant"""
    is_cons = False
    if character not in "aeiou":
        is_cons = True
    return is_cons

def to_piglatin(text):

    """takes a word and translates it into pig latin"""
    #convert input to list of lower case letters
    x = text.lower().split()
    print(x)
    if len(x) > 1:
        for word in x:
            front_cons = []
            word_as_list = [word]
            print("word_as_list =", word_as_list)
            for letter in word:
                if is_consonant(letter) == True:
                    print("letter =", letter)
                    front_cons.append(letter)
                    word_as_list.remove(letter)
                else:
                    break
            [word_as_list.append(front_cons[c]) for c in range(0, len(front_cons))]
            word_as_list.append("a")
            word_as_list.append("y")
            print(word_as_list)

test = "Hello there"

to_piglatin(test)

打印错误


我希望输出是 ellohay erethay 但我得到一个 Value Error list.remove(x) x not in list。

print 语句显示 word_as_list = ['hello'] 和 letter = h 但 word_as_list.remove(letter) 返回 ValueError

标签: python-3.xstringfunction

解决方案


在您的代码中,

word_as_list = [word]

制作一个长度为 1word = 'hello'的列表,其中 item 不是字符列表。您应该将其修改为:

word_as_list = list(word)

推荐阅读