usum_counts 136 uratio 10 uthreat_type_zh DDos攻击 usum_counts 0 uratio 10 uthreat_type_zh web攻击python判断列表中的字典threat_type_zh对应的value是否有攻击防护和DDos攻击如果都有则相加sum_counts的值给攻击防护如果threat_type_zh值只有攻击防护则不变如果如果th
您可以使用以下代码来实现您的需求:
threat_list = [{u'sum_counts': 136, u'ratio': 1.0, u'threat_type_zh': 'DDos攻击'}, {u'sum_counts': 0, u'ratio': 1.0, u'threat_type_zh': 'web攻击'}]
has_ddos = False
has_attack_protection = False
for threat in threat_list:
if threat['threat_type_zh'] == '攻击防护':
has_attack_protection = True
elif threat['threat_type_zh'] == 'DDos攻击':
has_ddos = True
if has_ddos and has_attack_protection:
for threat in threat_list:
if threat['threat_type_zh'] == '攻击防护':
threat['sum_counts'] += next((item['sum_counts'] for item in threat_list if item['threat_type_zh'] == 'DDos攻击'), 0)
threat_list = [threat for threat in threat_list if threat['threat_type_zh'] != 'DDos攻击']
elif has_ddos:
for threat in threat_list:
if threat['threat_type_zh'] == 'DDos攻击':
threat['threat_type_zh'] = '攻击防护'
print(threat_list)
这段代码首先遍历列表中的字典,检查是否存在'攻击防护'和'DDos攻击'。如果两者都存在,则将'DDos攻击'的sum_counts值添加到'攻击防护'的sum_counts值中,并删除'DDos攻击'字典。如果只存在'攻击防护',则不进行任何操作。如果只存在'DDos攻击',则将该字典的'threat_type_zh'修改为'攻击防护'。最后打印修改后的threat_list
原文地址: http://www.cveoy.top/t/topic/iRRD 著作权归作者所有。请勿转载和采集!