【问题标题】:python :- IndexError: list index out of range when converting list into dictionarypython :- IndexError: 将列表转换为字典时列表索引超出范围
【发布时间】:2019-09-26 12:56:33
【问题描述】:

想法是将“netsh wlan show interfaces”的输出放入字典中,以便可以根据键获取值。

观察到的错误是:

IndexError: 列表索引超出范围

import subprocess
results = subprocess.check_output("netsh wlan show interfaces")
results = results.decode("ascii")
results = results.replace("\r","")
ls = results.split("\n")
ls = ls[3:]
dict = {}
temp = []

for i in ls:
    temp = i.split(":")
    m = temp[0].strip()
    dict[m] = temp[1].strip()

print(dict)

【问题讨论】:

    标签: python-3.x dictionary netsh


    【解决方案1】:

    在命令输出的每一行中可能没有":",因此在假设i.split(":") 返回的列表中有多个项目之前,您应该使用if 语句来确保它确实如此:

    for i in ls:
        temp = i.split(":", 1)
        if len(temp) > 1:
            m = temp[0].strip()
            dict[m] = temp[1].strip()
    

    【讨论】:

    • 非常感谢您的帮助,您的意见帮助我把事情做好
    猜你喜欢
    • 2016-08-25
    • 2017-04-05
    • 2012-07-15
    • 2013-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多