Python跳过了我的if statemens

2024-09-28 03:21:46 发布

您现在位置:Python中文网/ 问答频道 /正文

由于某些原因,此代码不起作用:

def pyglatin(word):
    output = ""
    wordlenedit = len(word)-1
    wordlen = len(word)
    fixer = 0
    while fixer == 0:
        for i in word:
            if i == 'a' or i == 'e' or i == 'o' or i == 'i' or i == 'u':
                fixer = 1
            else:
                wordlenedit -= 1
    else:
        output = word[wordlenedit:wordlen:1] + '-' + word[0:wordlenedit:1] + 'ay'
        return output

要查看问题,请单击here。问题似乎是它跳过了识别元音的if语句,但我不确定原因。这会导致一些非常奇怪的输出。在


Tags: or代码foroutputlenifdef原因
2条回答

您的函数不起作用,因为您遍历单词,从wordlenedit = len(word)-1开始,减少遇到的每个辅音的拆分索引。在

for循环的末尾,wordlenedit等于(length of the word) - 1 - (number of consonants)。只有当单词中第一个元音索引(从0开始)等于元音数目-1时,函数才有效。在

另外,while循环在这里是无用的,因为您在for循环中遍历整个单词。更糟糕的是:如果你有一个没有元音的单词,while循环将是一个无限循环(比如“fly”,因为你没有检查“y”)

这是您函数的更正版本,使用关键字break

def pyglatin2(word):
    output = ""
    wordlenedit = 0
    wordlen = len(word)
    for l in word:
        if l == 'a' or l == 'e' or l == 'o' or l == 'i' or l == 'u':
            break
        else:
            wordlenedit += 1

    output = word[wordlenedit:wordlen:1] + '-' + word[0:wordlenedit:1] + 'ay'
    return output

但是,可以用更简洁/简单的方式编写此函数,使用Regular Expressions,如下所示:

^{pr2}$

如果要在不使用正则表达式的情况下执行此操作,最简单的方法是使用enumerate

def pyglatin(word):
    for i, ch in enumerate(word):
        if ch in 'aeiou':
            return word[i:] + '-' + word[:i] + 'ay'

相关问题 更多 >

    热门问题