gpt4 book ai didi

python - 按类的属性分组和计数

转载 作者:太空宇宙 更新时间:2023-11-04 07:49:51 25 4
gpt4 key购买 nike

我有一个结果类如下

class Result:
cluster = -1;
label = -1;

簇和标签都可以有 0-9 之间的值,我想做的是计算簇中标签的数量。目前我正在使用以下代码进行计数,但这不是一个优雅的解决方案。 resultList 是 Result 对象的列表。

countZero = 0;
countOne = 0;
countTwo = 0;
countThree = 0;
countFour = 0;
countFive = 0;
countSix = 0;
countSeven = 0;
countEight = 0;
countNine = 0;

for i in range(len(resultList)):
if resultList[i].cluster == 0:
if resultList[i].label == 0:
countZero = countZero + 1
if resultList[i].label == 1:
countOne = countOne + 1
if resultList[i].label == 2:
countTwo = countTwo + 1
if resultList[i].label == 3:
countThree = countThree + 1
if resultList[i].label == 4:
countFour = countFour + 1
if resultList[i].label == 5:
countFive = countFive + 1
if resultList[i].label == 6:
countSix = countSix + 1
if resultList[i].label == 7:
countSeven = countSeven + 1
if resultList[i].label == 8:
countEight = countEight + 1
if resultList[i].label == 9:
countNine = countNine + 1

print(countZero) #
print(countOne) #
print(countTwo) #
print(countThree) #
print(countFour) #
print(countFive) #
print(countSix) #
print(countSeven) #
print(countEight) #
print(countNine) #

如有任何关于寻找更好解决方案的建议或指导,我们将不胜感激。

最佳答案

Counter 函数返回一个字典,其中包含每个标签的计数。以这种方式将其用于集群 0:

from collections import Counter

Counter(resultList[resultList['cluster']==0]]['label'])

关于python - 按类的属性分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56498719/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com