简体   繁体   English

如何计算二维数组中某个键的出现次数?

[英]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'我收到一条错误消息,显示消息“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 :使用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 和 else 搞混了。 If key not in counts you should set it to one, not increment and the other way around.如果键不在计数中,则应将其设置为 1,而不是递增,反之亦然。

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.但是您可以做得更好,例如,按照@Chris 的建议,在扁平化列表上使用collections.Counter方法。 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] .因为sum(sq,[])只是[8, 6, 4, 1, 5, 8, 6, 4, 2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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