我该如何计算一个单词中辅音的数目呢?python

2024-07-03 05:58:34 发布

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

在python中,我如何计算一个单词中辅音的数量?我知道有几种不同的方法可以做到这一点,但我认为我的选择是分析一个单词的每个字母,并在遇到辅音时添加一个计数器。我就是不知道怎么去实现它。在

从这个开始?在

count = 0
consonant = 'astringofconsonants'
if consonant in string[0]:
    count += 1

Tags: 方法in数量stringifcount字母计数器
3条回答

可以像迭代列表一样迭代字符串:

for letter in word:
  if letter in consonants:
    # You can fill in from here

理解!在

count = sum(1 for c in cons if c not in ['a','e','i','o','u'])

从评论来看,可能更像Python:

^{pr2}$

你的开始不是很像Python。在

尝试使用遍历列表

for c in word:
    if c in consonants:
        # do something

您也可以使用如下所示的生成器。它将遍历每个字母并计算单词中每个辅音的数量。在

^{pr2}$

使用sum()函数将它们全部相加

相关问题 更多 >