多个单行for循环

时间:2018-04-05 14:31:44

标签: python python-2.7 for-loop

我正在使用此数据:NVD CVE data

我的代码是:

import json
with open('nvdcve-1.0-2018.json') as f:
    CVE = json.loads(f.read())

for x in CVE["CVE_Items"]:
    if x["cve"]["affects"]["vendor"]["vendor_data"]: # Check data exists
        description = x["cve"]["description"]["description_data"][0]["value"]
        cve = x["cve"]["CVE_data_meta"]["ID"]
        vendor = x["cve"]["affects"]["vendor"]["vendor_data"][0]["vendor_name"]
        product = x["cve"]["affects"]["vendor"]["vendor_data"][0]["product"]["product_data"][0]["product_name"]
        version = x["cve"]["affects"]["vendor"]["vendor_data"][0]["product"]["product_data"][0]["version"]["version_data"]
        version = [x["version_value"] for x in version]
        references = [x["url"] for x in x["cve"]["references"]["reference_data"]]
        print references

预期输出

[u'https://github.com/D0neMkj/POC_BSOD/tree/master/Advanced%20SystemCare%20Utimate/Monitor_win7_x64.sys-0x9c4060d0']

[u'https://github.com/D0neMkj/POC_BSOD/tree/master/Advanced%20SystemCare%20Utimate/Monitor_win7_x64.sys-0x9c402004']

[u'https://github.com/D0neMkj/POC_BSOD/tree/master/Advanced%20SystemCare%20Utimate/Monitor_win7_x86.sys-0x9c4060c4']

...
...

代码返回此错误

Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
KeyError: 'cve'

密钥'cve'确实存在:

>>> for x in CVE["CVE_Items"]:
...     x["cve"].keys()
...
[u'description', u'data_type', u'affects', u'data_format', u'problemtype', u'data_version', u'references', u'CVE_data_meta']
[u'description', u'data_type', u'affects', u'data_format', u'problemtype', u'data_version', u'references', u'CVE_data_meta']
[u'description', u'data_type', u'affects', u'data_format', u'problemtype', u'data_version', u'references', u'CVE_data_meta']
...
...

如果删除两个version =行(11-12),代码将按预期工作。

我认为问题更可能是我,而不是Python,但我想了解为什么在使用多个单行for循环时会出现此错误?

1 个答案:

答案 0 :(得分:0)

version = [x["version_value"] for x in version]
references = [x["url"] for x in x["cve"]["references"]["reference_data"]]

您经常使用x。为循环变量使用不同的名称。

version = [v["version_value"] for v in version]
references = [r["url"] for r in x["cve"]["references"]["reference_data"]]