1

I have an array that contains string elements:

farm = np.array(garden)

leads to this:

[['F' 'F' 'W' 'W']
 ['F' '_' '_' 'W']
 ['G' '_' '_' 'J']
 ['G' 'G' 'J' 'J']]

I want to count how many times lets say 'F' appears, is there a simple way to do this? This is a small version of the bigger array that I will be working on

2
  • Is this indeed a numpy array or a Python nested list of lists? Please format it to make it syntactically valid. And a hint: function collections.Counter() returns a dictionary of unique elements and their counts in a list. Commented Mar 25, 2018 at 16:47
  • Also, how many dimensions in your array? Is it 2 dimensions or 3? Commented Mar 25, 2018 at 16:58

3 Answers 3

2

EDIT: Lists have a count method. So your new and improved pythonic code is

D= sum([i.count("F") for i in listX])

Well you can make a function, that Checks if the parameter passed to it is in the array. You can even use list comprehensions. For example

F = sum([sum([1 for i in j if i=="f"]) for j in listX])
Sign up to request clarification or add additional context in comments.

1 Comment

Of course the more readable solution is to make a function; Also im not sure if there is a count method for lists
1

Michael's solution is the most "pythonic", but I wanted to offer an alternative solution using simpler constructs, in case you're just learning:

lst = []
lst.append(['F', 'F', 'W', 'W'])
lst.append(['F', '_', '_', 'W'])
lst.append(['G', '_', '_', 'J'])
lst.append(['G', 'G', 'J', 'J'])

numFs = 0
# Look at each sublist
for sublist in lst:
  # Look at each element within the sublist
  for s in sublist:
    # If the element is an 'F', add 1 to the number of Fs
    if s == 'F':
      numFs += 1
print(numFs)

Comments

0

You could also try to reduce and join the elements of the arrays into a string and then count, like so:

from functools import reduce
a = [['F' 'F' 'W' 'W'], ['F' '_' '_' 'W'], ['G' '_' '_' 'J'], ['G' 'G' 'J' 'J']]
c = ''.join(reduce(list.__add__, a)).count('F')
print(c)

When executed, this code prints:

3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.