给定一个无序的值列表,比如
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
当前回答
简单的解决方法就是用字典。
def frequency(l):
d = {}
for i in l:
if i in d.keys():
d[i] += 1
else:
d[i] = 1
for k, v in d.iteritems():
if v ==max (d.values()):
return k,d.keys()
print(frequency([10,10,10,10,20,20,20,20,40,40,50,50,30]))
其他回答
我使用计数器在1行代码中从文本文件单词生成一个frequency . dict
def _fileIndex(fh):
''' create a dict using Counter of a
flat list of words (re.findall(re.compile(r"[a-zA-Z]+"), lines)) in (lines in file->for lines in fh)
'''
return Counter(
[wrd.lower() for wrdList in
[words for words in
[re.findall(re.compile(r'[a-zA-Z]+'), lines) for lines in fh]]
for wrd in wrdList])
对于您的第一个问题,迭代列表并使用字典跟踪元素的存在。
对于你的第二个问题,只需使用集合操作符。
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
通过遍历列表并计算它们,手动计算出现的数量,使用collections.defaultdict跟踪到目前为止看到的内容:
from collections import defaultdict
appearances = defaultdict(int)
for curr in a:
appearances[curr] += 1
seta = set(a)
b = [a.count(el) for el in seta]
a = list(seta) #Only if you really want it.