Python 计算特定单词

Python 计算特定单词,python,string,list,function,sum,Python,String,List,Function,Sum,我正在研究一个函数,它可以计算单词的数量,包括缩略语,比如不能在一个只有五个字母的列表中 我在网上搜索了一个类似的问题,但结果是空手而归 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

我正在研究一个函数,它可以计算单词的数量,包括缩略语,比如不能在一个只有五个字母的列表中

我在网上搜索了一个类似的问题,但结果是空手而归

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))

我想用这个函数来计算一个列表中的单词数,包括缩略词,比如不能,总共五个字母。感谢您的反馈。

过滤器的另一种方式:

>>> def word5(wlist):
...     return len([word for word in wlist if len(word)==5])
...
>>> word5(["adsfe", "as", "jkiejjl", "jseke", "jjies"])
3
>>>
wordlist = ["adsfe", "as", "jkiejjl", "jseke", "jjies"]
len(list(filter(lambda x: len(x)==5, wordlist))) 

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

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

你可以这样做:

w5 = list(map(len,wordlist)).count(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))

我的原始帖子经过编辑以反映关于重复主题的问题。