簡體   English   中英

如何在循環中跟蹤元音索引

[英]How to keep track of vowel indices in a loop

我必須輸入一個單詞並跟蹤該單詞中所有元音的索引。 我的代碼適用於包含唯一元音的單詞,但只要元音重復,存儲的索引對於該特定元音都是相同的。

vowel_list = {'a','e','i','o','u'}

word_in = input('Give me a word: ')

# Internally convert the word to all lowercase to check against the vowel list.
word_new = word_in.lower()

# Keep track of how many vowels the loop detects and store that in a variable.
count_one = 0
# Keep a running index of when my loop detects vowels.
myindex = []

# Now go through input and check for vowels
for i in word_new:
    if i in vowel_list:
        count_one += 1
        myindex.append(word_new.index(i))
# Only value of the counter for no vowels is 0

例如,如果我輸入“Nina”,我會得到正確的myindex = [1, 3] 但是,當我輸入“Ana”時,我得到[0, 0]

任何想法為什么?

當您執行word_new.index(i) (其中i是某個元音)時,您基本上是在要求 python 在整個字符串中找到元音i第一個索引。

所以基本上對於“ana”:

  • 對於第一個“a”,您要求在“ana”中找到“a”的第一個索引,該索引位於 position 0。
  • 對於第二個“a”,您再次要求“ana”中“a”的第一個索引是 position 0。

為了簡單地解決問題,您還可以在迭代單詞時保留正在檢查的字符的索引。 這可以使用enumerate輕松完成。 您的 for 循環將如下所示:

for i, char in enumerate(word_new):
    if char in vowel_list:
        count_one += 1
        myindex.append(i)

這里i是您當前正在查看的字符的索引,而char是字符本身。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM