给定一个无序的值列表,比如
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 = [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
当前回答
另一种方法是使用较重但功能强大的库——NLTK。
import nltk
fdist = nltk.FreqDist(a)
fdist.values()
fdist.most_common()
其他回答
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]
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
假设我们有一个列表:
fruits = ['banana', 'banana', 'apple', 'banana']
我们可以在列表中找出每种水果的数量,像这样:
import numpy as np
(unique, counts) = np.unique(fruits, return_counts=True)
{x:y for x,y in zip(unique, counts)}
结果:
{'banana': 3, 'apple': 1}
还有一种方法是使用字典和列表。数数,下面一种幼稚的做法。
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)
我迟到了,但这也有用,也会帮助到其他人:
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]