尝试返回字符串中元音的索引

0 投票
2 回答
2815 浏览
提问于 2025-04-17 14:39

对于这段代码,我基本上已经让它能返回特定的索引,但它会在同一个索引位置计算多个元音字母。我刚意识到,index() 这个函数只会返回第一个出现的项,但现在我几乎用尽了其他的可能性。

def vowel_indices(s):
'string ==> list(int), return the list of indices of the vowels in s'
res = []
for vowel in s:
    if vowel in 'aeiouAEIOU':
        res = res + [s.index(vowel)]
return res

一个运行的例子是:

vowel_indices('hello world')

[1, 4, 7]

但我得到的结果却是 [1, 4, 4]。

2 个回答

1

你的问题在于,.index() 只会找到第一个出现的元音字母,所以后面重复的元音字母就被忽略了。

与其使用 .index(),不如用一个计数器变量(有点像 C++ 的 for 循环):

def vowel_indices(s):
    res = []
    index = 0

    for vowel in s:
        index += 1

        if vowel.lower() in 'aeiou':
            res.append(index)

    return res

或者可以使用 enumerate()

def vowel_indices(s):
    res = []

    for index, vowel in enumerate(s):
        if vowel.lower() in 'aeiou':
            res.append(index)

    return res
4

使用列表推导式配合 enumerate 函数:

vowel_indices = [idx for idx, ch in enumerate(your_string) if ch.lower() in 'aeiou']

撰写回答