简体   繁体   English

附加元音位置Python

[英]Appending Vowel Location Python

I am trying to figure out why I am getting an empty list when this code is ran. 我试图弄清楚为什么我在运行此代码时得到一个空列表。 The goal is to take a string, find the index of any vowels and append that index to a list. 目标是获取一个字符串,找到任何元音的索引并将该索引附加到列表中。 With an index starting at one instead of zero. 索引从1开始而不是零。 Any tips where the error might be occurring would be great! 任何可能发生错误的提示都会很棒! If there is a general oversight you notice please let me know. 如果您有通知疏忽,请通知我。 Relatively new to python. 相对较新的python。 thanks 谢谢

def vowel_indices(word):
    vowels = ["a", "e", "i", "o", "u"]
    vowel_idx = []
    word.lower() 
    for idx, letter in enumerate(word, start = 1):
        if letter == vowels:
            vowel_idx.append(idx) 
        return vowel_idx     

if letter == vowels: should be if letter in vowels: if letter == vowels:应该是if letter in vowels:

vowels is a list and a string can never be equal to a list and you should also move the return out of the loop as that will stop the function in it's track the first time it loops through 元音是一个列表,一个字符串永远不能等于一个列表,你也应该将返回值移出循环,因为它会在第一次循环时停止它的轨道中的函数

Method lower does not modify the string in-place (strings are immutable ), so you should instead do: 方法lower不会就地修改字符串(字符串是不可变的 ),所以你应该这样做:

word = word.lower()

Then to check for the membership of a character in the list of vowels , you should use the in operator and not == : 然后要检查vowels列表中字符的成员资格,您应该使用in运算符而不是==

if letter in vowels:

And then the return statement should not be placed inside the for loop as this will make the function return immediately after the first iteration, which is not what you intend: 然后return语句不应该放在for循环中,因为这会使函数在第一次迭代后立即返回,这不是你想要的:

for idx, letter in enumerate(word, start = 1):
    if letter in vowels:
        vowel_idx.append(idx) 
return vowel_idx 

On an additional note, you can be less verbose and do the entire operation using a list comprehension : 另外需要注意的是,使用列表推导可以减少冗长并完成整个操作:

def vowel_indices(word):
    return [idx for idx, l in enumerate(word.lower(), 1) if l in vowels]

It work great 它很棒

def vowel_indices(word):
    vowels = ["a", "e", "i", "o", "u"]
    word.lower()
    indexes = [index for c,index in zip(word,range(len(word))) if c in vowels]
    print(indexes)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM