Skip to main content
 首页 » 编程设计

python之使用嵌套循环计算项目

2025年05月04日9虾米姐

def count_vowel_phonemes(phonemes): 
    """ (list of list of str) -> int 
 
    Return the number of vowel phonemes in phonemes. 
 
    >>> phonemes = [['N', 'OW1'], ['Y', 'EH1', 'S']] 
    >>> count_vowel_phonemes(phonemes) 
    2 
    """ 
    number_of_vowel_phonemes = 0 
    for phoneme in phonemes: 
        for item in phoneme: 
            if 0 or 1 or 2 in item: 
                number_of_vowel_phonemes = number_of_vowel_phonemes + 1 
    return number_of_vowel_phonemes   

描述: 元音音素是最后一个字符为 0、1 或 2 的音素。例如,单词 BEFORE (B IH0 F AO1 R) 包含两个元音音素,单词 GAP (G AE1 P) 包含一个。

参数表示音素列表。功能是返回在音素列表列表中找到的元音音素的数量。 基本上这个问题要求我计算这个列表中的位数,但我的代码一直返回 0,这很奇怪。我的代码有问题吗?提前致谢!!

请您参考如下方法:

if any(i in item for i in ("0", "1","2"): 

您的代码实际上会为您的测试输入返回 5,因为 或 1 将始终评估为 True,您正在检查 bool (1) 没有实际检查 1 是否在 item 中并且您还在将 ints 与 strings 进行比较>。

您可以使用 sum 将代码缩减为生成器表达式,并使用 str.endswith 查找以 0,1 或 2 结尾的子元素:

return sum(item.endswith(("0","1","2")) for phoneme in phonemes for item in phoneme) 

哪些输出:

In [4]: phonemes = [['N', 'OW1'], ['Y', 'EH1', 'S']] 
In [5]: count_vowel_phonemes(phonemes) 
Out[5]: 2 

使用 或 进行测试的正确方法是:

if "0" in item or "1" in item or "2" in item: 

相当于 any 行。