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.

0

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.