[英]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.