python list.count总是返回0

时间:2017-12-03 18:16:20

标签: python list count

我有一个冗长的Python列表,并希望计算单个字符的出现次数。例如,总共有多少次' o'发生?我想要N = 4.

lexicon = ['yuo', 'want', 'to', 'sioo', 'D6', 'bUk', 'lUk'], etc.

list.count()是显而易见的解决方案。但是,它始终返回0.我寻找的角色并不重要。我已经仔细检查了我的文件 - 我正在搜索的字符肯定在那里。我碰巧在for循环中计算count():

for i in range(100): 
    # random sample 500 words 
    sample = list(set(random.sample(lexicon, 500)))
    C1 = ['k']
    total = sum(len(i) for i in sample) # total words
    sample_count_C1 = sample.count(C1) / total

但它在for循环之外返回0,超过列表' lexicon'同样。我不想要一份总数清单,所以我不认为Counter会有效。

想法?

3 个答案:

答案 0 :(得分:1)

如果我们选择您的list(您提供的缩短版本):

lexicon = ['yu', 'want', 'to', 'si', 'D6', 'bUk', 'lUk']

然后我们可以使用sum()generator-expression

来获取计数
count = sum(s.count(c) for s in lexicon)

所以如果c'k',那么这会2,因为k有两次出现。

这可以在for-loop或不在4中使用,因此您应该可以自己将其合并到更宽泛的代码中。

通过您的最新修改,我可以确认您在修改后的列表中为'o'生成了1的计数。

答案 1 :(得分:0)

如果我正确理解了您的问题,您可以计算列表中每个单词的每个字符的出现次数。这被称为频率分布。

以下是使用data-toggle

的简单实现
Counter

使用from collections import Counter lexicon = ['yu', 'want', 'to', 'si', 'D6', 'bUk', 'lUk'] chars = [char for word in lexicon for char in word] freq_dist = Counter(chars) Counter({'t': 2, 'U': 2, 'k': 2, 'a': 1, 'u': 1, 'l': 1, 'i': 1, 'y': 1, 'D': 1, '6': 1, 'b': 1, 's': 1, 'w': 1, 'n': 1, 'o': 1}) ,您可以返回角色的出现次数。

freq_dist

答案 2 :(得分:0)

它给出零,因为sample.count('K')将匹配k作为字符串。它不会考虑bukluk。 如果你想计算字符的频率就像这样

for i in range(100): 
     # random sample 500 words 
     sample = list(set(random.sample(lexicon, 500)))
     C1 = ['k']
     total = sum(len(i) for i in sample) # total words
     sample_count=sum([x.count(C1) for x in sample])
     sample_count_C1 = sampl_count / total