使用Python中的循环删除列表中的项目

Geo*_*lls 2 python

我对编程很新,并且已经开始使用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)
Run Code Online (Sandbox Code Playgroud)

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

例如:

anti_vowel("Hey look words!")    
returns: "Hy lk words!"
Run Code Online (Sandbox Code Playgroud)

有人可以解释我哪里出错了所以我可以从中学习吗?

谢谢 :)

Cor*_*mer 5

同时通过它迭代不应该从列表中删除项目.你会在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'
Run Code Online (Sandbox Code Playgroud)

写成一个函数,这将是

def anti_vowel(text):
    vowels = 'aeiouAEIOU'
    return filter(lambda letter : letter not in vowels, text)
Run Code Online (Sandbox Code Playgroud)

测试

>>> anti_vowel(myString)
'Ths s my strng tht hs vwls n t'
Run Code Online (Sandbox Code Playgroud)