简体   繁体   中英

How to count the number of occurrences of a key in a 2D array?

I have created a 2D array and I want to count the number of occurrences of each element in the array

This is the code I have written

sq=[[8,6,4],
 [1,5,8],
 [6,4,2]]

def counting(sq):
  counts={}
  for i in range(len(sq)):
    for j in range(len(sq[i])):
      if(sq[i][j] not in counts):
        counts[sq[i][j]]=1
      else:
        counts[sq[i][j]]+=1
  return counts        

I am getting an error, with the message 'KeyError: 8'

I want the output to be be

{8:2, 6:2, 4:2, 1:1, 5:1, 2:1}

One way using collections.Counter :

sum(map(Counter, sq), Counter())

Output:

Counter({1: 1, 2: 1, 4: 2, 5: 1, 6: 2, 8: 2})

You simply got the if and the else mixed up. If key not in counts you should set it to one, not increment and the other way around.

if(sq[i][j] not in counts):
    counts[sq[i][j]]=1
else:
    counts[sq[i][j]]+=1

Starting from your code example, I suggest you to iterate over the elements of the lists directly (without using an index). It is easier to read and you easily avoid the key error, as follows:

sq = [[8,6,4], [1,5,8], [6,4,2]]

def counting(sq):
  counts={}
  for i in sq:
    for j in i:
      if (j not in counts):
        counts[j] = 1
      else:
        counts[j] += 1
  return counts

print(counting(sq))
# {8: 2, 6: 2, 4: 2, 1: 1, 5: 1, 2: 1}

But you can do better, for example by using the collections.Counter method on the flattened list, as suggested by @Chris. I suggest you this solution:

from collections import Counter

sq = [[8,6,4], [1,5,8], [6,4,2]]

def counting(sq):
  flat_list = [j for i in sq for j in i]
  return Counter(flat_list)

print(counting(sq))
# Counter({8: 2, 6: 2, 4: 2, 1: 1, 5: 1, 2: 1})

I add this solution since nobody mentioned it yet:

from collections import Counter
sq = [[8,6,4], [1,5,8], [6,4,2]]
c = Counter(sum(sq,[]))

c
Counter({8: 2, 6: 2, 4: 2, 1: 1, 5: 1, 2: 1})

since sum(sq,[]) is just [8, 6, 4, 1, 5, 8, 6, 4, 2] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM