0

Hi all,

I'm fairly new to Python as a language but have some experience with C# and Javascript, so this may be a basic question.

I'm trying to count how many times a single character appears in a multi-dimensional array from a decided start and finish point within the array, and then assign this counted value to a variable. For example:

array1 = [['a', 1],['a', 4],['b', 3],['c', 4]]

I would then want to assign variable 'x' how many times a character like 'a' appears in the array from the starting position only to the third position in the array. My attempts at this are:

x = array1[0:2].count('a')
x = ('a' in array1[0:2]).count
x = count('a', beg= 0, end=2(array1))

I understand the solution may use indexing or something similar? I'm still new to the language and am struggling a little with the syntax, so apologies if the answer is blatantly obvious or I've misinterpreted something

Any help is much appreciated :)
Thanks

Community
  • 1
  • 1
MrYummy
  • 3
  • 3
  • You may find this [related post](https://stackoverflow.com/questions/17718271/python-count-for-multidimensional-arrays-list-of-lists) useful. Also, by "third position in the array", do you mean the third list within the outer list, or the third item overall (so, the 'a' in the second list)? – thisisbenmanley Apr 17 '20 at 05:09
  • @thisisbenmanley I mean the third list within the outer list, sorry for the confusion – MrYummy Apr 17 '20 at 05:11

2 Answers2

1

The elements of array1 are lists, not characters, which is why none of your attempts work. You need to test the first element of each of these nested lists, not the lists.

x = sum(x[0] == 'a' for x in array1[0:2])

Or you can extract the first elements and then use count()

x = list(x[0] for x in array1[0:2]).count('a')

Note also that in a slice, the selected indexes don't include the final index in the slice. 0:2 means elements 0 and 1. So if you want the first 3 elements of the list, it should be 0:3.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

As array1 is array of lists.You should check occurence of "a" in each of the lists up to index 3 of array1.

As you are beginner in python below is simple code for your problem.

array1 = [['a', 1],['a', 4],['b', 3],['c', 4]]
count=0
for ele in array1[:3]:
    for ele1 in ele:
        if ele1=="a":
            count+=1
print(count)

Output: 2

The first for loop traverses from 0 to 2 giving out element in array.

['a',1]
['a',4]
['b',3]

The next loop takes each ele and counts the value of "a".

Akash
  • 54
  • 4