Python循环程序

2024-10-02 18:20:45 发布

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

到目前为止,下面的程序的重点是从alphabet列表上的辅音位置迭代到alphabet列表的结尾,从而获得最接近的1元音。一旦循环找到最接近的(右边的)元音,循环应该停止迭代,并将该元音的索引和字母分配给afterVowel和{}变量。对每个辅音也应该这样做(也就是说,如果输入(word)的当前迭代是一个辅音,我们将它放在alphabet列表中,然后遍历alphabet列表,找到最接近右元音的,然后停止)。在

问题是,它迭代alphabet列表,并将所有元音输出到字母表中辅音的右边,而不是只输出一个。在

不幸的是,我尝试使用break,while循环和条件语句,以及其他技术,但没有任何效果。在

如何解决这个问题?在

下面的print语句用于检查是否输出了一个或多个元音;它不是程序的实际部分。在

def rovarspraket(word = raw_input("Please enter a word: ")):

    consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
    vowels = ['a','e','i','o','u']
    alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

    #1. Identify if the current element is a consonant, the consonant, and the consonant's index on alphabet list
    for character in range(len(word.lower())):
        for c in range(len(consonants)):
            if word[character] == consonants[c]:
                currentConsonant = word[character]

            #2. Determine After and Before vowels

                #After vowel 
                for a in range(alphabet.index(word[character]), len(alphabet)): 
                    for aV in range(len(vowels)):
                        if alphabet[a] == vowels[aV]:
                            afterVowel = alphabet[a]
                            afterVowelIndex = a
                            print afterVowel, afterVowelIndex 

Tags: thein列表forlenifrangeword
2条回答

break将退出一个循环。你需要一个标志来突破第二个阶段:

done = False

for a in range(alphabet.index(word[character]), len(alphabet)): 
    for aV in range(len(vowels)):
        if alphabet[a] == vowels[aV]:
            afterVowel = alphabet[a]
            afterVowelIndex = a
            print afterVowel, afterVowelIndex
            done = True
            break

    if done:
        break

我希望我能正确地理解你的问题。如果我是,你不能用一个布尔标志来解决这个问题吗?在

def rovarspraket(word = raw_input("Please enter a word: ")):

consonants = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
vowels = ['a','e','i','o','u']
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']

#1. Identify if the current element is a consonant, the consonant, and the consonant's index on alphabet list
for character in range(len(word.lower())):
    for c in range(len(consonants)):
        if word[character] == consonants[c]:
            currentConsonant = word[character]

        #2. Determine After and Before vowels

            #After vowel
            flag = False
            for a in range(alphabet.index(word[character]), len(alphabet)): 
                for aV in range(len(vowels)):
                    if alphabet[a] == vowels[aV] and not flag:
                        afterVowel = alphabet[a]
                        afterVowelIndex = a
                        print afterVowel, afterVowelIndex
                        flag = True

相关问题 更多 >