Python - 分组依据并过滤缺少的属性值

标签 python

我有一个列表,其中一些项目没有像 item["transitioned_to"] = 'Ended' 这样的属性我想计算有多少项目缺少此值。

我只能计算有多少项目具有“已结束”属性:data_filtered = list(filter(lambda x: x['transitioned_to'] == "Ended", steps)) - 每个Ended相对于单execution_id .

如何通过 execution_sid 聚合此列表?并计算丢失了多少元素 item["transitioned_to"] = 'Ended'

作为输入示例:

[{
    'execution_sid': 'sid1',
    'transitioned_from': 'step_a',
    'transitioned_to': 'step_b',
}, {
    'execution_sid': 'sid1',
    'transitioned_from': 'step_b',
    'transitioned_to': 'Ended',
}, {
    'execution_sid': 'sid2',
    'transitioned_from': 'step_a',
    'transitioned_to': 'step_b',
}]

在此示例中,应为每种情况返回 1:1 已结束,1 尚未结束。可以使用 python 执行此计数吗?

最佳答案

collections.defaultdict对象:

from collections import defaultdict

lst = [{'execution_sid': 'sid1', 'transitioned_from': 'step_a', 'transitioned_to': 'step_b', },
       {'execution_sid': 'sid1', 'transitioned_from': 'step_b', 'transitioned_to': 'Ended', },
       {'execution_sid': 'sid2', 'transitioned_from': 'step_a', 'transitioned_to': 'step_b', }]

res = defaultdict(int)
for d in lst:
    res[d['execution_sid']] += d['transitioned_to'] != 'Ended'

print(dict(res))

输出(由 execution_sid 聚合):

{'sid1': 1, 'sid2': 1}

关于Python - 分组依据并过滤缺少的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57254799/

相关文章:

python - 如何覆盖 GAE 中的 HTTP 请求动词

python - 如何使用 Python 列表使用 SWIG 在 C++ 中分配 std::vector?

Python 27 scpclient超时

python - 通过重复加法进行二进制乘法

python socket编程OSError : [WinError 10038] an operation was attempted on something that is not a socket

Python: type(i) 是 int... 但我是 int = False

python - Sparql 上的相同查询给出不同的结果

python - 重复 if 直到 true [python]

python - 类变量,instance.var 和 instance.__class__.var 的区别

python - 如何在 DRF 中对密码进行哈希处理?