给定一个无序的值列表,比如

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 = [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]

其他回答

简单的解决方法就是用字典。

def frequency(l):
     d = {}
     for i in l:
        if i in d.keys():
           d[i] += 1
        else:
           d[i] = 1

     for k, v in d.iteritems():
        if v ==max (d.values()):
           return k,d.keys()

print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))

另一种方法是使用较重但功能强大的库——NLTK。

import nltk

fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.

通过遍历列表并计算它们,手动计算出现的数量,使用collections.defaultdict跟踪到目前为止看到的内容:

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1
a=[1,2,3,4,5,1,2,3]
b=[0,0,0,0,0,0,0]
for i in range(0,len(a)):
    b[a[i]]+=1