You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于列表数据的键统计与条件过滤查询的技术咨询

列表数据的键统计与条件过滤查询的技术咨询

嘿,我懂你的需求啦——你想要针对这份包含多个字典的列表,根据某个键(host_serial)是否存在,来分别统计另一个键(.cn)的条目数量对吧?咱们一步步来解决这个问题。

首先先把你提供的原始数据整理完整(我补全了最后一条省略的内容,确保数据结构可用):

DEV_DATA = [
    {'.cn': 'DEVICE200002', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff23fd96'},
    {'.cn': 'DEVICE200003', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff245135'},
    {'.cn': 'DEVICE200111', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff24ab22'},
    {'ou_host_config': '&@#4e08ef42883a50fe823303bbff252729', '.cn': 'DEVICE200112'},
    {'ou_host_config': '&@#4e08ef42883a50fe823303bbff25a19d', '.cn': 'DEVICE200222'},
    {'ou_host_config': '&@#4e08ef42883a50fe823303bbff26405b', '.cn': 'DEVICE200057', 'host_serial': 'HO-STA-2103-2A77'},
    {'ou_host_config': '&@#4e08ef42883a50fe823303bbff267f56', '.cn': 'DEVICE200106', 'host_serial': 'HO-STA-2011-0A66'},
    {'ou_host_config': '&@#4e08ef42883a50fe823303bbff26cbb7', '.cn': 'DEVICE200116', 'host_serial': 'HO-STA-2011-0B14'},
    {'host_serial': 'HO-STA-2011-0BA3', '.cn': 'DEVICE200134', 'ou_host_config': '&@#4e08ef42883a50fe823303bbff270f99'}
]

接下来,我们用Python来实现这个统计需求,逻辑非常直观:

  1. 初始化两个计数器,分别记录**包含host_serial和不包含host_serial**的.cn条目数
  2. 遍历列表里的每一个字典
  3. 检查当前字典是否包含host_serial键,对应更新计数器

基础统计实现

# 初始化计数器
with_host_serial = 0
without_host_serial = 0

for item in DEV_DATA:
    # 先确认.cn键存在(避免键不存在报错)
    if '.cn' in item:
        if 'host_serial' in item:
            with_host_serial += 1
        else:
            without_host_serial += 1

# 输出结果
print(f"包含host_serial的.cn条目数量:{with_host_serial}")
print(f"不包含host_serial的.cn条目数量:{without_host_serial}")

运行这段代码后,你会得到:

包含host_serial的.cn条目数量:4
不包含host_serial的.cn条目数量:5

进阶:提取对应条目列表

如果你不仅需要计数,还想把两类条目分别提取出来,可以用列表推导式快速实现:

# 提取包含host_serial的设备.cn值列表
with_host = [item['.cn'] for item in DEV_DATA if '.cn' in item and 'host_serial' in item]
# 提取不包含host_serial的设备.cn值列表
without_host = [item['.cn'] for item in DEV_DATA if '.cn' in item and 'host_serial' not in item]

print("包含host_serial的设备列表:", with_host)
print("不包含host_serial的设备列表:", without_host)

这样就能轻松完成你的条件过滤和统计需求啦~

备注:内容来源于stack exchange,提问作者basicscripting

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 12:33:11