我是python的初学者,我对编码知之甚少 这就是我为维基百科所得到的:
答案 0 :(得分:2)
您可以使用collections.Counter
:
>>> from collections import Counter
>>> c1 = Counter(list1)
>>> c2 = Counter(list2)
>>> def rec_rank(key,dic):
... return dic[key]/float(sum(dic.values()))
...
>>> rec_rank('apple',c1)
0.3333333333333333
>>> rec_rank('apple',c2)
0.5
答案 1 :(得分:1)
你是说这个吗?
count = 0
for i in list:
if i == string:
count += 1.0
return count / len(list)
这是错误的。
答案 2 :(得分:1)
len(filter(lambda x: x == 'apple', list1)) / float(len(list1))
sum(map(lambda x: x == 'apple', list1)) / float(len(list1))
reduce(lambda x, y: x + (y == 'apple'), list1, 0.0) / len(list1)