我希望计算列表中相同值的元素数量并返回一个dict:
> a = map(int,[x**0.5 for x in range(20)])
> a
> [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
> number_of_elements_by_value(a)
> {0:1, 1:3, 2:5, 3:7, 4:4}
我想这是一种直方图?
答案 0 :(得分:8)
如果您没有collections.Counter
可用
from collections import defaultdict
d = defaultdict(int)
a = map(int, [x**0.5 for x in range(20)])
for i in a:
d[i] += 1
print d
答案 1 :(得分:7)
使用Counter:
>>> from collections import Counter
>>> a = map(int,[x**0.5 for x in range(20)])
>>> a
[0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
>>> c = Counter(a)
>>> c[2]
5
答案 2 :(得分:2)
使用count来获取列表中元素的计数并为唯一元素设置:
>>> l = [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
>>> k = [(x, l.count(x)) for x in set(l)]
>>> k
[(0, 1), (1, 3), (2, 5), (3, 7), (4, 4)]
>>>
>>>
>>> dict(k)
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}
>>>
答案 3 :(得分:0)
在有Counter之前,有groupby:
>>> a = map(int,[x**0.5 for x in range(20)])
>>> from itertools import groupby
>>> a_hist= dict((g[0],len(list(g[1]))) for g in groupby(a))
>>> a_hist
{0: 1, 1: 3, 2: 5, 3: 7, 4: 4}
(对于groupby为此目的而工作,输入列表a
必须按排序顺序排列。在这种情况下,a
已经排序。)