给定一个无序的值列表,比如
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
当前回答
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'])
其他回答
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
对于您的第一个问题,迭代列表并使用字典跟踪元素的存在。
对于你的第二个问题,只需使用集合操作符。
def frequencyDistribution(data):
return {i: data.count(i) for i in data}
print frequencyDistribution([1,2,3,4])
...
{1: 1, 2: 1, 3: 1, 4: 1} # originalNumber: count
通过遍历列表并计算它们,手动计算出现的数量,使用collections.defaultdict跟踪到目前为止看到的内容:
from collections import defaultdict
appearances = defaultdict(int)
for curr in a:
appearances[curr] += 1
num=[3,2,3,5,5,3,7,6,4,6,7,2]
print ('\nelements are:\t',num)
count_dict={}
for elements in num:
count_dict[elements]=num.count(elements)
print ('\nfrequency:\t',count_dict)