简体   繁体   English

多个单行循环

[英]Multiple single-line for loops

I am using this data: NVD CVE data 我正在使用以下数据: NVD CVE数据

My code is: 我的代码是:

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

Expected output 预期产量

[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']

...
...

The code returns this error 代码返回此错误

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

The key 'cve' does exist: 关键'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']
...
...

If I remove the two version = lines (11-12), the code works as expected. 如果我删除了两个version =行(11-12),代码将按预期工作。

I'm thinking the issue is more likely to be me, rather than Python, but I'd like to understand why this error is raised when using multiple single-line for loops? 我认为问题很可能是我自己,而不是Python,但我想了解为什么在使用多个单行for循环时会引发此错误?

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

You're using x too often. 您经常使用x Use a different name for the loop variables. 为循环变量使用其他名称。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM