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

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

当前回答

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

其他回答

我使用计数器在1行代码中从文本文件单词生成一个frequency . dict

def _fileIndex(fh):
''' create a dict using Counter of a
flat list of words (re.findall(re.compile(r"[a-zA-Z]+"), lines)) in (lines in file->for lines in fh)
'''
return Counter(
    [wrd.lower() for wrdList in
     [words for words in
      [re.findall(re.compile(r'[a-zA-Z]+'), lines) for lines in fh]]
     for wrd in wrdList])

还有一种方法是使用字典和列表。数数,下面一种幼稚的做法。

dicio = dict()

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

b = list()

c = list()

for i in a:

   if i in dicio: continue 

   else:

      dicio[i] = a.count(i)

      b.append(a.count(i))

      c.append(i)

print (b)

print (c)
from collections import Counter
a=["E","D","C","G","B","A","B","F","D","D","C","A","G","A","C","B","F","C","B"]

counter=Counter(a)

kk=[list(counter.keys()),list(counter.values())]

pd.DataFrame(np.array(kk).T, columns=['Letter','Count'])

你可以这样做:

import numpy as np
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
np.unique(a, return_counts=True)

输出:

(array([1, 2, 3, 4, 5]), array([4, 4, 2, 1, 2], dtype=int64))

第一个数组是值,第二个数组是具有这些值的元素的数量。

所以如果你想要得到一个数字数组,你应该使用这个:

np.unique(a, return_counts=True)[1]
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.