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

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

当前回答

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

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

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

a = list(set(a))

其他回答

我将简单地以以下方式使用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

对于一个无序列表,你应该使用:

[a.count(el) for el in set(a)]

输出为

[4, 4, 2, 1, 2]

您可以使用python中提供的内置函数

l.count(l[i])


  d=[]
  for i in range(len(l)):
        if l[i] not in d:
             d.append(l[i])
             print(l.count(l[i])

上面的代码自动删除列表中的重复项,并打印原始列表和没有重复项的列表中每个元素的频率。

一枪双鸟!X维

from collections import OrderedDict
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
def get_count(lists):
    dictionary = OrderedDict()
    for val in lists:
        dictionary.setdefault(val,[]).append(1)
    return [sum(val) for val in dictionary.values()]
print(get_count(a))
>>>[4, 4, 2, 1, 2]

删除副本并维持秩序:

list(dict.fromkeys(get_count(a)))
>>>[4, 2, 1]

这个答案更加明确

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

d = {}
for item in a:
    if item in d:
        d[item] = d.get(item)+1
    else:
        d[item] = 1

for k,v in d.items():
    print(str(k)+':'+str(v))

# output
#1:4
#2:4
#3:3
#4:2

#remove dups
d = set(a)
print(d)
#{1, 2, 3, 4}