【问题标题】:Count the number of elements of same value in Python [duplicate]计算Python中相同值元素的数量[重复]
【发布时间】:2011-05-07 03:05:16
【问题描述】:

可能重复:
How to count the frequency of the elements in a list?

我希望计算列表中相同值元素的数量并返回一个字典:

> 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}

我猜它是一种直方图?

【问题讨论】:

  • 我没有投反对票,但这可能是因为您可以通过几秒钟的搜索找到答案,因为它可能是最受骗的问题之一。
  • 提到的“重复”没有回答这个问题,因为 Theodor 要求一个 dict 作为结果,这正是我正在寻找的。stackoverflow.com/questions/2161752/… 给出了不同的输出。 - 赞成 :-)

标签: python counter histogram


【解决方案1】:

如果您没有可用的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

【讨论】:

  • 谢谢,效果很好。我可能应该像上面提到的那样更新 Python,但时间总是很短;)
【解决方案2】:

使用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

【讨论】:

  • 正如 Mark Byers 所说,Counter 仅在 Python 2.7+ 中可用。但我认为是时候更新我的 2.6.6 了;)
【解决方案3】:

使用 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}
>>> 

【讨论】:

  • 这个效率很低,l.count(x)每次都会扫描整个列表
【解决方案4】:

在有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 已经排序。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-22
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多