繁体   English   中英

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

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

我创建了一个二维数组,我想计算数组中每个元素的出现次数

这是我写的代码

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        

我收到一条错误消息,显示消息“KeyError: 8”

我希望输出是

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

使用collections.Counter一种方法:

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

输出:

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

你只是把 if 和 else 搞混了。 如果键不在计数中,则应将其设置为 1,而不是递增,反之亦然。

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

从您的代码示例开始,我建议您直接迭代列表的元素(不使用索引)。 更容易阅读,也轻松避免关键错误,如下:

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}

但是您可以做得更好,例如,按照@Chris 的建议,在扁平化列表上使用collections.Counter方法。 我建议你这个解决方案:

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})

我添加了这个解决方案,因为还没有人提到它:

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})

因为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