使用嵌套循环计数项

2024-10-02 08:29:23 发布

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

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(bih0fao1r)包含两个元音音素,而单词GAP(gap1p)则有一个。在

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


Tags: orofinnumber列表forcountitem
1条回答
网友
1楼 · 发布于 2024-10-02 08:29:23
if any(i in item for i in ("0", "1","2"):

您的代码实际上会为您的测试输入返回5,因为or 1的计算结果总是True,您检查的是{}而不是实际检查{}是否在{}中,并且还将ints与{}进行比较。在

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

^{pr2}$

哪些输出:

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

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

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

相当于any行。在

相关问题 更多 >

    热门问题