我刚开始在codacademy学习Python。我试图做反元音功能,但发现以下问题' u'。
def anti_vowel(text):
a = []
for i in text:
a.append(i)
for item in a:
if item in "aeiouAEIOU":
a.remove(item)
print ''.join(a)
print anti_vowel("Hey You!")
print anti_vowel("Hey look Words!")
print anti_vowel("aeiouAEIOU")
打印
"Hy Yu!"
"Hy lk Words!"
"eoAIU"
而不是
"Hy Y!"
"Hy lk Wrds!"
""
不知何故,有些元音没有被删除。
我发现了很多替代功能。 但是,请帮我识别当前代码的错误。
答案 0 :(得分:3)
不需要使用删除功能,也无需迭代两次。相反,当您迭代时,检查该项是否为元音,如果不是,则仅附加。
def anti_vowel(text):
a = []
for i in text:
if i not in "aeiouAEIOU":
a.append(i)
print ''.join(a)
答案 1 :(得分:1)
当你仔细观察剩余的元音时,你可以看到所有这些元音仍然紧随其后。在你的上一个例子中,a(删除)e(停留)i(删除)o(停留)等等。
这是因为您正在迭代列表并同时修改它。
要解决此问题,您应该复制列表。然后,您可以在修改副本时迭代原始的。
答案 2 :(得分:1)
迭代时删除项目不是一个好主意。
在一行中将生成器理解传递给str.join
def anti_vowel(text):
return ''.join(item for item in text if item not in "aeiouAEIOU")
或者使用set
进行更快速的字母查找可能更高效(不确定转换为小写会加快速度,因为它会为此创建一个新字符串)
s=set("aeiouAEIOU")
def anti_vowel(text):
return ''.join(item for item in text if item not in s)
答案 3 :(得分:1)
就像其他人已经说过的那样,你在修改列表时会修改它。我确实想为这个任务建议一个python内置选项,但对于3.x> Python > 2.6:
print "Hey You!".translate(None, "aeiouAEIOU")
在Python 3.x中,您需要考虑标准Unicode字符串并首先进行翻译:
translation = dict.fromkeys(map(ord, "aeiouAEIOU"), None)
print("Hey You!".translate(translation))
答案 4 :(得分:0)
def anti_vowel(text):
a = []
for i in text:
a.append(i)
b = a[:]
for item in a:
if item in "aeiouAEIOU":
b.remove(item)
print (''.join(b))
print (anti_vowel("Hey You!"))
print (anti_vowel("Hey look Words!"))
print (anti_vowel("aeiouAEIOU"))
答案 5 :(得分:0)
为什么不像这样递归尝试?
def anti_vowel(s):
if not s:
return s
elif s[0] in "aeiouAEIOU":
return anti_vowel(s[1:])
return s[0] + anti_vowel(s[1:])
print (anti_vowel("Hey You!"))
print (anti_vowel("Hey look Words!"))
print (anti_vowel("aeiouAEIOU"))
输出:
Hy Y!
Hy lk Wrds!
答案 6 :(得分:0)
您在遍历时从列表中删除项目,以便创建问题。 此外,没有必要遍历这么多次。
你可以使用:
<table border=1>
<tr>
<td>First cell in first table. The cell to the right has the second table in it.</td>
<td>
<table>
<tr><td>nested table</td></tr>
<tr><td>nested table</td></tr>
</table>
</td>
</tr>
</table>
或者我会说,而不是像这样使用列表使用字符串:
def anti_vowel(text):
a = []
for i in text:
if i not in "aeiouAEIOU":
a.append(i)
print ''.join(a)
编辑:
使用def anti_vowel(text):
a = ""
for item in text:
if item not in "aeiouAEIOU":
a+=item
print a
比使用@jan在评论部分中指出的字符串cancatenation更快。
答案 7 :(得分:0)
您还可以加入列表理解的结果,例如:
def anti_vowel(text):
return "".join([char for char in text if char not in "aeiouAEIOU"])
如果您希望该功能不仅仅是打印到终端(例如,如果您想以某种方式使用返回的值),请确保让您的函数返回结果。无需打印打印其结果的函数的结果并返回None
(如果内部没有return
语句就是这种情况。)
列表推导的[char for char in text ...]
部分只是对名为text
的字符串中的字符的for循环。 [... if char not in "aeiouAEIOU"]
排除了"aeiouAEIOU"
字符串中出现的字符。最后,"".join([ ... ])
将未排除的字符合并在一起,形成一个返回return
语句的字符串。