Removing items for a list using a loop in Python

前端 未结 5 1200
深忆病人
深忆病人 2020-12-12 00:17

I am very new to programming in general and have started with Python. I am working through various problems to try and better my understanding.

I am trying to defin

5条回答
  •  情歌与酒
    2020-12-12 01:11

    You should not delete items from a list while iterating through it. You will find numerous posts on Stack Overflow explaining why.

    I would use the filter function

    >>> 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'
    

    Written as a function, this would be

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

    Test

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

提交回复
热议问题