给定一个无序的值列表,比如
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
当前回答
假设我们有一个列表:
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}
其他回答
计算元素的频率可能最好使用字典:
b = {}
for item in a:
b[item] = b.get(item, 0) + 1
要删除重复项,请使用set:
a = list(set(a))
对于一个无序列表,你应该使用:
[a.count(el) for el in set(a)]
输出为
[4, 4, 2, 1, 2]
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
我迟到了,但这也有用,也会帮助到其他人:
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]
对于您的第一个问题,迭代列表并使用字典跟踪元素的存在。
对于你的第二个问题,只需使用集合操作符。