gpt4 book ai didi

python - 在 Python 中使用循环删除列表项

转载 作者:行者123 更新时间:2023-11-28 20:22:00 25 4
gpt4 key购买 nike

总体而言,我对编程还很陌生,刚开始使用 Python。我正在努力解决各种问题以尝试加深我的理解。

我正在尝试定义一个从字符串中删除元音的函数。这是我尝试过的:

def anti_vowel(text):
new = []
for i in range(len(text)):
new.append(text[i])
print new
for x in new:
if x == "e" or x == "E" or x == "a" or x == "A" or x == "i" or x == "I" or x == "o" or x == "O" or x == "u" or x == "U":
new.remove(x)
return "".join(new)

这是从字符串的第一个单词中删除元音,但不是最后一个单词:

例如:

anti_vowel("Hey look words!")    
returns: "Hy lk words!"

有人可以解释我哪里出错了,以便我从中吸取教训吗?

谢谢:)

最佳答案

should not delete items from a list while iterating through it .您会在 Stack Overflow 上找到许多解释原因的帖子。

我会使用filter 函数

>>> vowels = 'aeiouAEIOU'
>>> myString = 'This is my string that has vowels in it'
>>> filter(lambda i : i not in vowels, myString)
'Ths s my strng tht hs vwls n t'

写成一个函数,就是

def anti_vowel(text):
vowels = 'aeiouAEIOU'
return filter(lambda letter : letter not in vowels, text)

测试

>>> anti_vowel(myString)
'Ths s my strng tht hs vwls n t'

关于python - 在 Python 中使用循环删除列表项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25326339/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com