【问题标题】:Simple way to count number of specific elements in 2D array Python [duplicate]计算二维数组Python中特定元素数量的简单方法[重复]
【发布时间】:2017-03-29 00:20:04
【问题描述】:

我正在寻找一种方法来计算我正在使用的二维数组中有多少特定字符的实例。例如,当我打印出数组时,它可能如下所示:

[['.', '.'], ['.', 'R']]

有时这个数组会更大,我正在寻找一种很好的方法来获取诸如“R”之类的实例的数量,以便我可以在未来的 if 语句中使用它。

【问题讨论】:

    标签: python arrays python-2.7 multidimensional-array count


    【解决方案1】:

    更简洁的方式是:

    def countChar(char, list):
        return sum([i.count(char) for i in list])
    

    这不需要是一个函数,你可以像这样使用它:

    test=[['x','r','a'],['r','t','u'],['r','r','R']]
    sum([i.count('r') for i in test])
    

    返回 4。

    【讨论】:

      【解决方案2】:

      除非我完全误解了你的问题,否则这应该很适合你。

      def count_chars(char, list):
          count = 0
          for element in list:
              count += element.count(char)
          return count
      

      我确信有一种更高效的方法可以做到这一点,但我会把它留给你去探索;)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-25
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-15
        相关资源
        最近更新 更多