当列表中的项为非时,python索引超出范围

2024-09-30 01:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直得到IndexError: list index out of range,但我知道问题出在我映射的json中。你知道吗

server_names_and_ips = [
            (x['virtualMachine']['name'], x['virtualMachine']['network']['publicIpAddresses'][0]['ipAddress']) for x in
            s if x['virtualMachine']['network']['publicIpAddresses'][0]['ipAddress'] is not None]

问题是x['virtualMachine']['network']['publicIpAddresses'][0]['ipAddress']在返回的一个项中有一个值是[]。我试着把它的if条件,但没有正确的工作。我写if条件的方式有问题吗?想要的结果是谁…如果它有[]不要将该项添加到列表中并移到下一项。你知道吗


Tags: ofjsonindexifservernamesrangenetwork
1条回答
网友
1楼 · 发布于 2024-09-30 01:21:06

尝试检查列表是否包含任何元素:

server_names_and_ips = [
        (x['virtualMachine']['name'], x['virtualMachine']['network']['publicIpAddresses'][0]['ipAddress']) for x in
        s if len(x['virtualMachine']['network']['publicIpAddresses']) > 0 and x['virtualMachine']['network']['publicIpAddresses'][0]['ipAddress'] is not None]

相关问题 更多 >

    热门问题