python怎么將數(shù)據(jù)分類并計(jì)數(shù)

小億
128
2024-05-27 14:15:15

要將數(shù)據(jù)分類并計(jì)數(shù),可以使用字典來(lái)存儲(chǔ)數(shù)據(jù)分類的結(jié)果。以下是一個(gè)示例代碼:

data = [1, 2, 3, 1, 2, 1, 3, 4, 5, 4]

count_dict = {}

for item in data:
    if item in count_dict:
        count_dict[item] += 1
    else:
        count_dict[item] = 1

print(count_dict)

運(yùn)行以上代碼后,輸出結(jié)果為:

{1: 3, 2: 2, 3: 2, 4: 2, 5: 1}

這樣就可以將數(shù)據(jù)分類并計(jì)數(shù),得到每個(gè)元素出現(xiàn)的次數(shù)。

0