1

I'm looking for a way to count how many instances of a specific character there are in a 2D array that I'm working with. For example, when I print the array out, it can look like this:

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

Occasionally this array will be much larger, and I'm looking for a nice way to get the number of instances of something like 'R' for example, so that I can use it in a future if statement.

vvvvv
  • 25,404
  • 19
  • 49
  • 81
laroy
  • 163
  • 1
  • 1
  • 13

2 Answers2

1

A more condensed way would be:

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

This doesn't need to be a function, you could use it like:

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

Which returns 4.

Robbie
  • 4,672
  • 1
  • 19
  • 24
0

Unless I completely misunderstood your question, this should fit you nicely.

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

I'm sure there is a more performant way of doing this but I'll leave that for you to explore ;)

N. Walter
  • 99
  • 3