当前位置: 动力学知识库 > 问答 > 编程问答 >

Does the Python have something like reference in PHP?

问题描述:

I want to get some data from XML and return it in the same variable, so i do like this before return:

for element in response:

document = parseString(element)

try:

element = {

'scopes': document.getElementsByTagNameNS('*', 'Scopes')[0].firstChild.nodeValue,

'address': document.getElementsByTagNameNS('*', 'XAddrs')[0].firstChild.nodeValue

}

except:

element = False

return response

But the response still contains raw xml data instead of parsed results... Basically I want that element = ... value returned to response value.

网友答案:

Edit: Improving the answer according delnan and jonrsharpe.

The problem with your code is that, when you loop

for element in response

in each iteration element will be pointing to a new created object couse the lines:

element = {
            'scopes':  document.getElementsByTagNameNS('*', 'Scopes')[0].firstChild.nodeValue,
            'address': document.getElementsByTagNameNS('*', 'XAddrs')[0].firstChild.nodeValue
        }

and the object it was pointing before still the same. You can try this.

for index,element in enumerate(response):
    document = parseString(element)

    try:
        response[index]= {
            'scopes':  document.getElementsByTagNameNS('*', 'Scopes')[0].firstChild.nodeValue,
            'address': document.getElementsByTagNameNS('*', 'XAddrs')[0].firstChild.nodeValue
        }
    except:
         response[index]= False

return response
网友答案:

Assuming that response is a list of strings and you want to replace those strings with the parsed elements dict..., that's easy. Since lists are mutable containers, you can replace the elements as you go. No need to return the list... the one you pass in is changed.

def convert_response_to_elements(response):
    for index, element_str in enumerate(response):
        document = parseString(element_str)
        try:
            element = {
                'scopes':  document.getElementsByTagNameNS('*', 'Scopes')[0].firstChild.nodeValue,
                'address': document.getElementsByTagNameNS('*', 'XAddrs')[0].firstChild.nodeValue
        }
        except:
            element = False
        response[index] = element
网友答案:

Since response is a list, I would use pythons list comprehension. This will create new list without modifying old one.

new_response = [modify_element(element) for element in response]

Later if you want to remove elements that equal to False you can use filter function:

without_false = filter(lambda element: bool(element), new_response)
分享给朋友:
您可能感兴趣的文章:
随机阅读: