Python pop()函数在for循环中无法正常运行

Python pop()函数在for循环中无法正常运行,python,for-loop,Python,For Loop,代码如下: vowels = ['a','e','i','o','u'] def anti_vowel(text): tlength = len(text) words = [] result = "" for word in range(len(text)): words.append(text[word]) print words for index, word in enumerate(words):

代码如下:

vowels = ['a','e','i','o','u']

def anti_vowel(text):
    tlength = len(text)
    words = []
    result = ""
    for word in range(len(text)):
        words.append(text[word])
        print words
    for index, word in enumerate(words):
        if word.lower() in vowels:
            words.pop(index)
    for old_word in words:
        result += str(old_word)
    return result

print anti_vowel("Hey look words!")
预期结果:“Hy lk wrds!” 明显的结果:“海乐话!”


我不明白为什么循环会跳过列表中索引5上的“o”。我知道我可以用另一种方法,将非元音单词添加到列表中并组合它们,但我想知道如何为上述代码获得所需的结果。

您正在删除字符,但您的
索引
正在使用。所以元音不再在索引中了,你想

最好不要更改for循环中的列表,而是创建一个新列表:

def anti_vowel(text):
    words = []
    for character in text:
        if not (character.lower() in vowels or character.upper() in vowels):
            words.append(character)
    return ''.join(words)
或使用生成器表达式:

def anti_vowel(text):
    return ''.join(c for c in text if c.lower() not in vowels)
要删除单个元素时,必须使用while循环:

def anti_vowel(text):
    text = list(text)
    index = 0
    while index < len(text):
        if text[index].lower() in vowels:
            del text[index]
        else:
            index += 1
    return ''.join(text)
def反_元音(文本):
text=列表(text)
索引=0
当索引
我的输出是->
Hy-lok wrds
你在迭代时修改
单词
。在使用
str
转换之前,
old\u word
是什么类型?如果
元音
都是小写,为什么要与大写比较?@PeterWood我应该添加一个原始输入()生成器的效率低于
str.join
中的列表理解,而不是将某些内容硬编码到调用函数的语句中。谢谢你的回答丹尼尔,是的,我已经说过了,我知道。所以基本上你的意思是,当我从列表中删除/弹出内容时,索引将继续,弹出过程就像是一个缓慢的过程,无法在上一个索引旁边的“o”处同步索引?没有办法纠正这个吗?(我不擅长解释东西……请原谅)那么,如果你知道正确而优雅的解决方案,为什么要采用复杂且容易出错的方法呢?@Daniel它效率较低,因为必须创建生成器。注意一个相关的问题。