字符串的频率计数

时间:2014-11-29 03:17:42

标签: python string count

我有这个函数返回值列表和整数值的计数。我想改变它以返回字符串的计数和值,因为我在实现时遇到了麻烦。它适用于整数值但不适用于字符串。

def frequencies(xs):
 ys = sorted(xs)
 values, count = [], []
 for y in ys:
     if y not in values:
         values.append(y)
         count.append(1)
     else:
         count[-1] += 1
 return values, count

2 个答案:

答案 0 :(得分:1)

使用itertools.groupby

>>> import itertools
>>> a = [1,2,3,4,5,6,2,3,4,5,3,7,8,4,5,6,3]
>>> [ [x,len(list(y))] for x,y in itertools.groupby(sorted(a))]  # if you want list
[[1, 1], [2, 2], [3, 4], [4, 3], [5, 3], [6, 2], [7, 1], [8, 1]] 
>>> {x:len(list(y)) for x,y in itertools.groupby(sorted(a))}     # if you want dictionary
{1: 1, 2: 2, 3: 4, 4: 3, 5: 3, 6: 2, 7: 1, 8: 1}

答案 1 :(得分:0)

为什么重新发明轮子,而不是使用Counter?据我所知,你试图完全达到Counter的作用。

from collections import  Counter 

a = Counter([1,2,3,2,3,4,5,3,4,3,4,2,1,2,5])
print(a.keys(), a.values())


b = Counter(["1","2","3","2","3","4","5","3","4",'3','4','2','1','2','5'])
print(b.keys(), b.values())

给出:

dict_keys([1, 2, 3, 4, 5]) dict_values([2, 4, 4, 3, 2])
dict_keys(['4', '2', '3', '1', '5']) dict_values([3, 4, 4, 2, 2])