python-3.x - 猪拉丁函数代码列表中的值错误。当 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
解决方案
在您的代码中,
word_as_list = [word]
制作一个长度为 1word = 'hello'
的列表,其中 item 不是字符列表。您应该将其修改为:
word_as_list = list(word)
推荐阅读
- php - Vestacp php 7.2.* 升级破坏了 Ubuntu Digital Ocean 上的 nginx 和 php-fpm
- amazon-web-services - 是否可以压缩 AWS S3 中已有的文件?
- python - Python:默认字典初始化
- c++ - C ++中二进制数组中最大连续的开始和结束索引
- go - 在 go 中复制一个文件夹
- c++ - Gcov 覆盖率:我们可以只覆盖文件中的几行代码吗?
- javascript - 在 vue js 2.0 中集成客户端库(adminLTE)的正确方法
- python - 以下使用字典的python代码的时间复杂度是多少?
- webpack - 使用 webpack 从静态文件夹目录导入图片名称
- mysql - 错误 DbVisualizer 创建触发器