0

I am trying to find the mode of an array then count how many times that number appears in the array. However the way the problem I am trying to solve is set up has nested arrays so the [1] index in each array (the string) is irrelevant. How do I run this code to only apply to the [0] index of all the nested arrays?

from statistics import mode

arr = [[1,'cat'][1,'dog'][2,'fish']]
modeNum = mode(arr)
print(arr.count(modeNum))

2 Answers2

0

Assuming you want to find the mode of [1,1,2] following your example, you could use a comprehension list such as

numbers = [x[0] for x in arr]

Then find the mode with mode(numbers)

MikeMajara
  • 922
  • 9
  • 23
0

You can do this using generators. The counting line (with print) is taken from What is a good way to do countif in Python

from statistics import mode

arr = [[1,'cat'][1,'dog'][2,'fish']]
modeNum = mode(x[0] for x in arr)
print(sum(1 for x in arr if x[0] == modeNum))
Simon Crane
  • 2,122
  • 2
  • 10
  • 21
  • Would you say the OP's question is a duplicate of the question you linked to? – wwii Sep 30 '19 at 18:39
  • The linked question is about counting occurrences of a known value, like "5". OP also wants to know to find the mode of their list, which is not covered there, but might be somewhere else. – Simon Crane Sep 30 '19 at 18:41