使用while循环从函数返回变量

问题描述 投票:0回答:1

我是Python的新手,因此提前道歉!我试图从一个函数返回两个列表,其中while循环读取一个xml文件。我无法弄清楚该怎么做。我指的是下面代码中的imres(整数)和subres(2个整数),在循环中找到~10次。 Debuging显示变量在循环中正确填充,但我不知道如何返回填充列表,而是获取空列表。谢谢。

def getresolution(node):
    imres = []
    subres = []
    child4 = node.firstChild
    while child4:
                ...
        for child8 in keepElementNodes(child7.childNodes):
            if child8.getAttribute('Hash:key') == 'ImageSize':
                X = float(child8.getElementsByTagName('Size:width')[0].firstChild.data)
                Y = float(child8.getElementsByTagName('Size:height')[0].firstChild.data)
                imres += [[X, Y]]
            if child8.getAttribute('Hash:key') == 'Resolution':
                subres += [int(child8.firstChild.data)]
        getresolution(child4)
        child4 = child4.nextSibling
    return [imres, subres]


[imres, subres] = getresolution(xml_file)
python list while-loop return assign
1个回答
0
投票

未经测试,但这应该指向正确的方向:

def getresolution(node):
    imres = []
    subres = []
    child4 = node.firstChild
    while child4:
                ...
        for child8 in keepElementNodes(child7.childNodes):
            if child8.getAttribute('Hash:key') == 'ImageSize':
                X = float(child8.getElementsByTagName('Size:width')[0].firstChild.data)
                Y = float(child8.getElementsByTagName('Size:height')[0].firstChild.data)
                imres += [[X, Y]]
                if child8.getAttribute('Hash:key') == 'Resolution':
                    subres += [int(child8.firstChild.data)]
        t_imres, t_subres = getresolution(child4)
        imres += t_imres
        subres += t_subres
        child4 = child4.nextSibling
    return [imres, subres]


[imres, subres] = getresolution(xml_file)
© www.soinside.com 2019 - 2024. All rights reserved.