Python中的列表:具有特定长度的单词的总和

2024-05-16 11:45:17 发布

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

我是Python新手,我不确定我的语法或逻辑有什么问题,因为这看起来相当简单。我需要把单词分成字符吗

Count how many words in a list have length 5.

这就是我到目前为止所做的:

def countWords(lst):
    total=0
    for word in lst:
        if len(word)==5:
            total+=1
    return total

更新:这里有很好的答案和解释,谢谢!不幸的是,我认为activecode在这个站点上不起作用:https://runestone.academy/runestone/books/published/thinkcspy/Lists/Exercises.html:问题10


Tags: incount语法逻辑字符单词manylist
3条回答

代码正确,将为您提供长度为5的单词总数

您不需要计算单词的单个字符,因为len(str)提供了单词中的字符总数

为了使此解决方案更具可扩展性,并可针对不同长度的单词进行测试,可以在函数参数中提供长度作为选项。将默认字长设置为5默认值,并在函数内部检查它。为它添加代码

def countWords(lst,word_length=5):
    total=0
    for word in lst:
        if len(word)==word_length:
            total+=1
    return total

如果你想在一行解决方案

def countWords(lst, word_length=5):
    return sum(1 for word in lst if len(word)==word_length)

首先必须修复缩进,然后可能需要为sum变量使用另一个名称。我已为您将其更改为下面的found

def countWords(lst):
   found = 0
   for word in lst:
      if len(word) == 5:
         found += 1
   return found

然后你必须调用这个函数,所以

countWords(lst)

其中lst是单词列表

首先,缩进在Python中非常重要,还应避免使用sum、len等内置名称。此外,函数名应为小写,单词之间用下划线分隔。这是多行解决方案

def count_words(lst):
    word_count = 0
    for word in lst:
        if len(word) == 5:
            word_count += 1
    return word_count

这是一个线性解决方案

def count_words(lst):
    return len([word for word in lst if len(word) == 5])

相关问题 更多 >