【问题标题】:How do you begin a new loop when a certain character is found in a previous loop?当在前一个循环中找到某个字符时,如何开始一个新循环?
【发布时间】:2018-03-06 16:52:23
【问题描述】:

具体来说,用户输入一个单词。我想编制一份所有使用的元音和辅音的列表(没有重复,只是对每个使用的元音和辅音进行注释)。但是,我只想在找到单词中的最后一个元音后开始计算辅音。

例如,如果输入是“hello”,它应该计数 e,o,但不包括辅音,因为在最后一个元音之后有 non,计数 vowels=2,consonants=0。如果输入是“swarm”,它应该计算 a, r, m, vowels=1, consonants=2。 “书”会给你 o,k,vowels=1, consonants=1。

我希望程序满足其他条件,但这是第一步,也是最重要的开始。

这是我所拥有的,但它没有按我的需要工作(因为字母表的每个字母都有一行,我将只使用引号来显示语句的延续):

for i, ch in enumerate(word):
    if ch in VOWELS:
        if ch=="a" and ch not in VL:
            VL=VL+"a"
            VC+=1
        if ch=="e" and ch not in VL:
            VL=VL+"e"
            VC+=1
        #" " for each other vowel
    if ch not in VOWELS:
        if ch=="b" and ch not in CL:
            CL=CL+"b"
            CC+=1
        if ch=="c" and ch not in CL:
            CL=CL+"c"
            CC+=1
        #" " for each other consonant
print(VL[1:])
print(VC)
print(CL[1:])
print(CC)

我已经尝试在元音搜索完成后才开始缩进辅音部分,但是,这似乎不起作用。我需要索引最后一个元音的位置,然后开始辅音循环。

另一方面,我们只执行非常基本的命令,例如布尔、连接和字符串方法。没有字典或列表或类似的东西。我很确定有一种简单的方法可以做到这一点,但我似乎无法弄清楚。

【问题讨论】:

    标签: python methods boolean


    【解决方案1】:

    与其只计算第一个元音后的辅音,为什么不每次都计算,而是在找到元音时重置结果?

        if ch=="a" and ch not in VL:
            VL=VL+"a"
            VC+=1
            CL = ""  # add these two lines to each condition
            CC = 0
    

    而且由于我无法抗拒,代码可以变得更短更高效:

    VL = set()
    CL = set()
    
    for ch in word:
        if ch in VOWELS:
            VL.add(ch)
            CL = set()
        else:
            CL.add(ch)
    
    VC = len(VL)
    CC = len(CL)
    

    【讨论】:

    • 不能与更短更高效争论!我将尝试重置所有内容,看看它是否适用于我需要添加的其他一些条件。其他的更容易,所以这应该可以解决更多的问题。
    【解决方案2】:

    在循环遍历单词时,您还可以使用 i 值向后循环遍历其字符。然后,我们使用布尔值来确定我们的向后搜索是否已经击中元音,并且只计算击中第一个元音之前的辅音:

    vowels = 'aeiou'
    
    VL=''
    VC=0
    
    CL=''
    CC=0
    
    word = 'hello'
    count_cons = True
    for i, c in enumerate(word):
        if c in vowels and c not in VL:
            VL += c
            VC += 1
    
        if word[-i-1] in vowels:
            count_cons = False
        elif count_cons:
            CL += word[-i-1]
            CC += 1
    
    print(VL)
    print(VC)
    print(CL)
    print(CC)
    

    打印出来:

    eo
    2
    
    0
    

    如果你想缩短它,你可以这样做:

    VL = set(c for c in word if c in vowels)
    CL = set(c for i, c in enumerate(word) 
             if c not in vowels and all(x not in vowels for x in word[i+1:]))
    VC = len(VL)
    CC = len(CL)
    
    print(VL)
    print(CL)
    print(VC)
    print(CC)
    

    【讨论】:

    • 啊!使用 VL 计算 VC 比每次添加一个单独的命令要好得多。这肯定会缩短代码。并且向后循环应该可以解决问题,尽管我将不得不以相反的顺序打印它们......它们需要按照写入的顺序出现在打印中。但这可以通过以下方式完成:print(CL[-1:],对吗?
    • 应该是 print(CL[::-1])
    • 是的,你确实可以那样做。你也可以将CL += word[-i-1]改为CL = word[-i-1] + CL
    猜你喜欢
    • 2020-01-26
    • 2022-10-14
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多