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

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

当前回答

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]

其他回答

seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.
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

我找到了另一种方法,使用集合。

#ar is the list of elements
#convert ar to set to get unique elements
sock_set = set(ar)

#create dictionary of frequency of socks
sock_dict = {}

for sock in sock_set:
    sock_dict[sock] = ar.count(sock)
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

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

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

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

a = list(set(a))