Python覆盖列表值

2024-05-03 04:44:39 发布

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

我正在尝试解析一些XML文件。。但由于某些原因,它甚至会覆盖列表值,即使我附加到列表中

此处代码:

def parseXML():
    xmlfiles = glob.glob('./*.xml')
    temp = {}

    for host in xmlfiles:
        tree = ET.parse(host)
        root = tree.getroot()

        for wizard in tree.findall('.'):
            for grandpa in wizard:
                for parent in grandpa:
                    if parent.get('addr') != None:
                        ip = parent.get('addr')
                        temp[ip] = {}
                    for child in parent:
                        if child.get('portid') != None:
                            for grandchild in child:
                                if grandchild.get('name') != None:
                                    name = grandchild.get('name')
                                    if child.get('portid') not in temp:
                                        temp[ip][name] = []
                                        temp[ip][name].append(child.get('portid'))
                                    else:
                                        print (temp + " else")


    print (temp)

预期结果:

{'127.0.0.2': {'ssh': ['22'], 'http': ['80','8080']}, '127.0.0.1': {'ssh': ['22'], 'http': ['80','8080']}}

但我得到的却是:

{'127.0.0.2': {'ssh': ['22'], 'http': ['8080']}, '127.0.0.1': {'ssh': ['22'], 'http': ['8080']}}

Tags: nameinipnonechildtreehttpfor
1条回答
网友
1楼 · 发布于 2024-05-03 04:44:39
temp[ip][name] = []
temp[ip][name].append(child.get('portid'))

你在每次追加前都要清空你的列表。尝试将第一行移到它当前所在的if块上方

相关问题 更多 >