如何在列表中只获得一个元音?

How to only get one vowel in a list?

提问人:RykerStrike 提问时间:11/13/2023 更新时间:11/13/2023 访问量:49

问:

如果字符串多次包含元音,我无法让函数仅打印一次元音。这是任务:

编写 Python 函数 vowelList,该函数接受一个字符串参数并计算并返回所有参数的列表 该字符串中的元音。每个元音只需要在列表中列出一次,并且不应该有 小写元音和大写元音的区别。例如,函数调用 vowelList(“密西西比州”)。 应该返回 ['I'],因为 'i' 是输入字符串中唯一的元音。

我需要的输出是:

['O'] 

我不断得到的输出是:

['O', 'O']

这是我所拥有的:

def vowelList(s):
    low = s.lower()
    L = []
    vowels = "aeiou"
    for char in low:
        if char not in L and char in vowels:
            L.append(char.upper())
    return L

print(vowelList("book"))
python 列表 函数 追加

评论

3赞 ewokx 11/13/2023
char是,但你最终将 大写,并且你正在将(小写)与大写字符列表进行比较。vowelsOchar

答:

0赞 nontoxicguy 11/13/2023 #1

将大写字母附加到 L,但检查其中是否有小写字母。从一开始就将字符串设置为大写字母也会更好。

up = s.upper()
L = []
vowels = "AEIOU"
for char in up:
    if char not in L and char in vowels:
        L.append(char)
0赞 User12345 11/13/2023 #2

你可以改变

if char not in L and char in vowels:

if char in vowels and char.upper() not in L:

示例代码如下:

def vowelList(s):
    low = s.lower()
    L = []
    vowels = "aeiou"
    for char in low:
        if char in vowels and char.upper() not in L:
            L.append(char.upper())
    return L

print(vowelList("book"))

下面是示例输出:enter image description here

0赞 Veltzer Doron 11/13/2023 #3

使用集合 {} 而不是列表,它使解决方案更漂亮,在理论和美学上更具吸引力。