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

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

当前回答

我将简单地以以下方式使用scipy.stats.itemfreq:

from scipy.stats import itemfreq

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]

freq = itemfreq(a)

a = freq[:,0]
b = freq[:,1]

您可以在这里查看文档:http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.itemfreq.html

其他回答

计算元素的频率可能最好使用字典:

b = {}
for item in a:
    b[item] = b.get(item, 0) + 1

要删除重复项,请使用set:

a = list(set(a))
#!usr/bin/python
def frq(words):
    freq = {}
    for w in words:
            if w in freq:
                    freq[w] = freq.get(w)+1
            else:
                    freq[w] =1
    return freq

fp = open("poem","r")
list = fp.read()
fp.close()
input = list.split()
print input
d = frq(input)
print "frequency of input\n: "
print d
fp1 = open("output.txt","w+")
for k,v in d.items():
fp1.write(str(k)+':'+str(v)+"\n")
fp1.close()

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

from collections import defaultdict

appearances = defaultdict(int)

for curr in a:
    appearances[curr] += 1

还有另一种不使用集合的算法解决方案:

def countFreq(A):
   n=len(A)
   count=[0]*n                     # Create a new list initialized with '0'
   for i in range(n):
      count[A[i]]+= 1              # increase occurrence for value A[i]
   return [x for x in count if x]  # return non-zero count

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

import nltk

fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()