如何删除列表中的所有辅音和打印元音

时间:2018-02-22 14:30:44

标签: python-2.7 containers

这是我的代码:

#Alphabet class
class Alphabet(object):

        def __init__(self, s):
            self.s = s

        def __str__(self):
            return "Before: " + str(self.s)


#Define your Vowels class here
class Vowels:
        def __init__(self,vowelList):
                self.vowelList = vowelList

        def __str__(self):
                return "Invoking the method in Vowels by passing the Alphabet object\nAfter: " + str(vowelList)

        def addVowels(self,a_obj):
                for letter in a_obj:
                    if letter in 'aeiou':
                        vowelList.append(letter)
                        l = ','.join(vowelList)

a1 = Alphabet('A,B,C,E,I')
print a1
b = Vowels(a1)
b.addVowels(a1)
print (a2)

现在,所有打印都是“之前:A,B,C,E,I”,但是我试图用逗号分隔一串字母(即a_obj),从字符串中提取元音,然后将结果追加到列表中。我已经查看了有关查找和打印元音的其他答案,这就是为什么我在addVowels中有for循环和if语句,但没有运气。需要注意的是,元音应该是Alphabet的容器​​类。

当试图获得输出时......下面的代码给了我

a1 = Alphabet('A,B,C,E,I')
print a1
a2 = Vowels(a1)
print a2

输出中:

Before: A,B,C,E,I
Invoking the method in Vowels by passing the Alphabet object
After: []
好像它没有传递来自Alphabet的字母......

2 个答案:

答案 0 :(得分:0)

您可以使用split创建列表并删除一行中的逗号。

>>> "a,b,c,d,e,f,g,h,i,j".split(",")
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

从那里你可以通过只保留元音来删除辅音。 你可以使用for循环:

letterList = ['a', 'b', 'c', 'd']
vowelList = []

for letter in letterList:
    if letter in 'aeiou':
        vowelList.append(letter)

或者你可以使用列表理解:

letterList = ['a', 'b', 'c', 'd']
vowelList = [letter for letter in letterList if letter in 'aeiou']

这对您的代码有用的示例:

class Vowels(object):
    def __init__(self, vowelList):
        self.vowelList = vowelList

        lettersList = self.vowelList.s.split(",")
        self.vowelList = [letter for letter in self.lettersList if letter in 'aeiou']

答案 1 :(得分:0)

我正在使用此代码,它适用于我。

def getVowels(text):

vowel_letters = []
vowel_list = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U',]

for vowels in text:
    if vowels in vowel_list:
        vowel_letters.append(vowels)

return vowel_letters

print(getVowels('Hi, How are you today!'))
## Output: ['i', 'o', 'a', 'e', 'o', 'u', 'o', 'a']