gpt4 book ai didi

python - 根据另一个列表中的值操作字典列表

转载 作者:太空宇宙 更新时间:2023-11-04 06:50:03 26 4
gpt4 key购买 nike

所以基本上我有三个这样的列表:

list1 = [{
'IP' : "1.1.1.1",
'ID' : 1,
},
{
'IP' : "2.2.2.2",
'ID' : 2
}]

list2 = [{
'vulnerability_id' : 4567,
'ID' : 1,
},
{
'vulnerability_id' : 6578,
'ID' : 2
}]

list3 = [{
'vulnerability_id' : 4567,
'description' : 'blah',
},
{
'vulnerability_id' : 6578,
'description' : 'blah blah'
}]

我需要做的是获取基于 IP 的漏洞描述,但这可能需要某种列表理解,我不确定如何去做。 (并将其放入新词典中)

我需要检查我拥有的 IP 值,比如 1.1.1.1,然后将它的 ID 与 list2 进行比较,然后比较 list3 中关联的“vulnerability_id”。

任何帮助将不胜感激,如果这没有意义,请说出来,我会尝试和扩展。

最佳答案

这在计算方面确实很繁重,但您只有列表作为数据源,所以,这是我的“解决方案”:

results = []
for ip_info in list1:
result = {}
result['ip'] = ip_info['IP']
result['vulnerability'] = next((
vuln_info['vulnerability_id']
for vuln_info in list2
if vuln_info['ID'] == ip_info['ID']
),None)

result['description'] = next((
desc_info['description']
for desc_info in list3
if desc_info['vulnerability_id'] == result['vulnerability']
),None)

results.append(result)

结果:

[{'description': 'blah', 'ip': '1.1.1.1', 'vulnerability': 4567},
{'description': 'blah blah', 'ip': '2.2.2.2', 'vulnerability': 6578}]

编辑:根据我的回答和@Alex Hall 的回答进行改进:

def find(l, match, v, k):
return next((x[k] for x in l if x[match] == v), None)

results = []
for ip_info in list1:
ip = ip_info['IP']
_id = ip_info['ID']
vul = find(list2, 'ID', _id, 'vulnerability_id')
desc = find(list3, 'vulnerability_id', vulnerability, 'description')
results.append(dict(ip=ip, vulnerability=vul, description=desc))

关于python - 根据另一个列表中的值操作字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37368075/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com