【问题标题】:python .count for multidimensional arrays (list of lists)python .count 用于多维数组(列表列表)
【发布时间】:2020-12-14 21:35:43
【问题描述】:

如何计算由嵌套列表组成的多维数组中某个值的出现次数?如在以下列表中查找“foobar”时:

list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]

它应该返回2

(是的,我知道我可以编写一个循环来搜索所有内容,但我不喜欢这种解决方案,因为它相当耗时,(编写和运行时))

.count 可能吗?

【问题讨论】:

    标签: python


    【解决方案1】:
    >>> list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
    >>> sum(x.count('foobar') for x in list)
    2
    

    【讨论】:

      【解决方案2】:

      首先join the lists together using itertools,然后使用Collections module 计算每次出现的次数:

      import itertools
      from collections import Counter
      
      some_list = [['foobar', 'a', 'b'], ['x', 'c'], ['y', 'd', 'e', 'foobar'], ['z', 'f']]
      totals = Counter(i for i in list(itertools.chain.from_iterable(some_list)))
      print(totals["foobar"])
      

      【讨论】:

        【解决方案3】:
        >> from collections import Counter
        >> counted = Counter([item for sublist in my_list for item in sublist])
        >> counted.get('foobar', 'not found!')
        >> 2
        #or if not found in your counter
        >> 'not found!'
        

        这使用了子列表的展平,然后使用collections 模块和Counter 产生字数。

        【讨论】:

          猜你喜欢
          • 2013-05-17
          • 2014-11-26
          • 2015-05-22
          • 2012-04-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多