Collections.Counter 添加零计数元素

问题描述 投票:0回答:1

我有这段代码来分析我的数据的

node.properties
json 字典:

def summarise_all_model_properties(
    all_nodes: list
) -> defaultdict[str, Counter[str]]:

    propdicts = defaultdict(Counter)
    for node in all_nodes:
        propdicts[node.model_type].update(
            k for k in node.properties.keys() if node.properties[k]
        )

    return propdicts

每次

node.properties[propertyName]
不是空/假值时都正确计数。这给出了所有非空白属性及其计数的列表,按
node.model_type

分组

但是我也想知道任何存在但为空的节点属性,并在

Counter
中报告 0,例如现在我有(伪代码)

foo.properties = {"a": "something!", "b": '', "c": 123}
bar.properties = {"a": "", "b": '', "c": "something else!"}

all_nodes = [foo,bar]

Counter({"a": 1, "c": 2})

但我想包括 b 即使它在数据中总是空的

Counter({"a": 1, "b":0, "c": 2})

更新

这是因为我稍后有一些代码将属性 + 非空白用法的计数打印到具有 2 列的表中,并且我提前不知道所有属性名称(它们来自读取 json 文件)

for model_type, counter in summarise_all_model_properties(all_nodes).items():
    for propname, count in counter.items():
        csv.writerow(model_type, propname, count)
python python-3.x counter
1个回答
0
投票

A

Counter
就像一本字典。收集计数后,您始终可以设置默认值。

c = Counter({"a": 1, "c": 2})
c.setdefaults('b', 0)
c
# returns:
Counter({'c': 2, 'a': 1, 'b': 0})

这样做的好处是,如果它被包含在内,也不会覆盖

b
的计数。

© www.soinside.com 2019 - 2024. All rights reserved.