Removing items for a list using a loop in Python

前端 未结 5 1195
深忆病人
深忆病人 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:15

    You seem to have approached this a bit backwards. Firstly, note that:

    new = []
    for i in range(len(text)):
        new.append(text[i])
    

    is just:

    new = list(text)
    

    Secondly, why not check before appending, rather than afterwards? Then you only have to iterate over the characters once. This could be:

    def anti_vowel(text):
        """Remove all vowels from the supplied text.""" # explanatory docstring
        non_vowels = [] # clear variable names
        vowels = set("aeiouAEIOU") # sets allow fast membership tests
        for char in text: # iterate directly over characters, no need for 'i'
            if char not in vowels: # test membership of vowels
                non_vowels.append(char) # add non-vowels only
        return "".join(non_vowels)
    

    A quick example:

    >>> anti_vowel("Hey look words!")
    'Hy lk wrds!'
    

    This simplifies further to a list comprehension:

    def anti_vowel(text):
        """Remove all vowels from the supplied text."""
        vowels = set("aeiouAEIOU")
        return "".join([char for char in text if char not in vowels])
    

提交回复
热议问题