【问题标题】:Counting occurrence of non-specified values from 2d array in Python在 Python 中计算二维数组中非指定值的出现次数
【发布时间】:2015-02-16 13:34:38
【问题描述】:

我有一个类似的数组:

[['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 2291], ['fuubar', 8291]]

我想计算list[i][0] 中的相同值,而不指定我要查找的字符串。我在 Internet 上找到的示例要么是关于一维数组,要么是有规范的。如果我有一个非常简单的一维数组:
示例 1 指定值 (1)

[1, 2, 3, 4, 1, 4, 1].count(1)
3

示例 2 未指定要查找的内容

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

我想要的输出将是相似的。以我的例子为例,我想知道“foo”出现了多少次,“bar”出现了多少次,“fuubar”出现了多少次。但是如何使用 2D 数组做到这一点?

【问题讨论】:

  • 请注意,0091 不再是有效的文字。它曾经是一个字面八进制数。

标签: python arrays


【解决方案1】:

使用生成器表达式提取您要计数的项目:

>>> from collections import Counter
>>> l = [['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 91], ['fuubar', 8291]]
>>> Counter(item[0] for item in l)
Counter({'foo': 2, 'bar': 2, 'fuubar': 1})

【讨论】:

    【解决方案2】:
    Counter([z[0] for z in [['foo', 9283], ['bar', 7172], ['bar', 9890], ['foo', 91], ['fuubar', 8291]]])
    

    【讨论】:

      【解决方案3】:

      你可以解压:

      Counter(s for s, _ in l))
      

      或者对于功能性方法:

      from operator import itemgetter
      print(Counter(map(itemgetter(0), l)))
      

      【讨论】:

        猜你喜欢
        • 2021-09-02
        • 2022-01-07
        • 2016-01-19
        • 2011-05-07
        • 2023-04-02
        • 2020-09-23
        • 1970-01-01
        • 1970-01-01
        • 2015-03-13
        相关资源
        最近更新 更多