0

このコードでは、特定のインデックスを返すようにほとんど持っていますが、同じインデックス内の複数の母音をカウントします。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]を取得することになります。

4

2 に答える 2

4

リストコンプを使用してくださいenumerate

vowel_indices = [idx for idx, ch in enumerate(your_string) if ch.lower() in 'aeiou']
于 2013-02-04T00:12:02.207 に答える
1

問題は.index()、母音の最初の出現で停止することです。そのため、後で来る重複した母音は気づかれません。

を使用する代わりに、カウンター変数(C ++ループ.index()のようなもの)を使用します。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
于 2013-02-04T00:16:09.703 に答える