给定一个无序的值列表,比如
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
我怎样才能得到出现在列表中的每个值的频率,就像这样?
# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output
给定一个无序的值列表,比如
a = [5, 1, 2, 2, 4, 3, 1, 2, 3, 1, 1, 5, 2]
我怎样才能得到出现在列表中的每个值的频率,就像这样?
# `a` has 4 instances of `1`, 4 of `2`, 2 of `3`, 1 of `4,` 2 of `5`
b = [4, 4, 2, 1, 2] # expected output
当前回答
def frequencyDistribution(data):
return {i: data.count(i) for i in data}
print frequencyDistribution([1,2,3,4])
...
{1: 1, 2: 1, 3: 1, 4: 1} # originalNumber: count
其他回答
另一种方法是使用较重但功能强大的库——NLTK。
import nltk
fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()
对于一个无序列表,你应该使用:
[a.count(el) for el in set(a)]
输出为
[4, 4, 2, 1, 2]
我迟到了,但这也有用,也会帮助到其他人:
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq_list = []
a_l = list(set(a))
for x in a_l:
freq_list.append(a.count(x))
print 'Freq',freq_list
print 'number',a_l
会产生这个…
Freq [4, 4, 2, 1, 2]
number[1, 2, 3, 4, 5]
Python 2.7+引入了字典理解。从列表中构建字典将获得计数并去除重复项。
>>> a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
>>> d = {x:a.count(x) for x in a}
>>> d
{1: 4, 2: 4, 3: 2, 4: 1, 5: 2}
>>> a, b = d.keys(), d.values()
>>> a
[1, 2, 3, 4, 5]
>>> b
[4, 4, 2, 1, 2]
str1='the cat sat on the hat hat'
list1=str1.split();
list2=str1.split();
count=0;
m=[];
for i in range(len(list1)):
t=list1.pop(0);
print t
for j in range(len(list2)):
if(t==list2[j]):
count=count+1;
print count
m.append(count)
print m
count=0;
#print m