Python中按布尔属性(含None)统计列表对象数量的方法咨询
解决方案
Python 标准库的 collections.Counter 完全可以满足你的需求,你之前觉得不适用大概率是没有提前提取目标属性,正确实现如下:
from collections import Counter class MyObject(): def __init__(self, moniker, booleanVariable): self.name = moniker self.state = booleanVariable def _myCounterMethod(obj_list): # 提取所有对象的state属性传入Counter完成统计 state_counter = Counter(obj.state for obj in obj_list) # 按你需要的固定顺序和字符串键格式返回结果 return [ ('True', state_counter[True]), ('False', state_counter[False]), ('None', state_counter[None]) ] # 测试用例 myList = [] myList.append(MyObject("objectOne", True)) myList.append(MyObject("objectTwo", False)) myList.append(MyObject("objectThree", None)) counts = _myCounterMethod(myList) print(counts) # 输出:[('True', 1), ('False', 1), ('None', 1)]
方案优势
- 写法简洁符合Pythonic规范,不需要手动维护多个计数变量、写分支判断
- 执行效率高于纯Python层级的遍历实现,
Counter核心统计逻辑由C实现,数据量越大性能优势越明显 - 后续拓展性强,如果需要新增统计的state取值,只需修改返回列表即可
内容的提问来源于stack exchange,提问作者farAndAway
相关产品推荐
相关产品推荐

