【问题标题】:Counting particular words [duplicate]计算特定单词[重复]
【发布时间】:2019-10-16 14:04:46
【问题描述】:

我正在开发一个函数,该函数可以计算恰好有五个字母的列表中单词的数量(包括像 can't 这样的缩略词)。

我在互联网上搜索了类似的问题,但空手而归。

def word_count(wlist):
    """ This function counts the number of words (including contractions like couldn't) in a list w/ exactly 5
        letters."""
    w = 0
    for word in x:
        w += 1 if len(word) == 5 else 0
    return w

x = ["adsfe", "as", "jkiejjl", "jsengd'e", "jjies"]    
print(word_count(x))

我希望这个函数可以计算列表中的单词数量(包括像 can't 这样的缩写词)正好有五个字母。感谢您提供任何反馈。

【问题讨论】:

  • 我的原始帖子已被编辑以反映有关重复主题的问题。

标签: python string list function sum


【解决方案1】:
>>> def word5(wlist):
...     return len([word for word in wlist if len(word)==5])
...
>>> word5(["adsfe", "as", "jkiejjl", "jseke", "jjies"])
3
>>>

【讨论】:

    【解决方案2】:

    过滤器的另一种方式:

    wordlist = ["adsfe", "as", "jkiejjl", "jseke", "jjies"]
    len(list(filter(lambda x: len(x)==5, wordlist))) 
    

    【讨论】:

      【解决方案3】:

      提供不涉及列表理解的答案,以防它可能更容易理解。

      def word5(wlist):
          cnt=0
          for word in wordList:
              cnt += 1 if len(word) == 5 else 0
          return cnt
      

      【讨论】:

        【解决方案4】:

        你可以这样做:

        w5 = list(map(len,wordlist)).count(5)
        

        【讨论】:

          【解决方案5】:

          具有较小内存占用的紧凑替代方案:

          def word5(wlist, n=5):
              return sum((1 for word in wlist if len(word) == n))
          

          这也有效,但速度慢了大约 2.5 倍:

          def word5(wlist, n=5):
              return sum((int(len(word) == n) for word in wlist))
          

          【讨论】:

            猜你喜欢
            • 2016-04-10
            • 2020-10-04
            • 1970-01-01
            • 1970-01-01
            • 2020-07-28
            • 2013-12-06
            • 2017-10-09
            • 2011-04-25
            • 1970-01-01
            相关资源
            最近更新 更多