5

etreeを使用してxmlファイルを繰り返し処理しています。

import xml.etree.ElementTree as etree
tree = etree.parse('x.xml')
root = tree.getroot()
for child in root[0]:
 for child in child.getchildren():
        for child in child.getchildren():
            for child in child.getchildren():
               print(child.attrib)

これらのネストされたforループを回避するためのPythonの慣用的な方法は何ですか。

  getchildren() ⇒ list of Element instances [#]
    Returns all subelements. The elements are returned in document order.

Returns:
A list of subelements.

SOで、 ネストされたforループを回避するような投稿を見まし たが、私の使用には直接変換されません。

ありがとう。

4

2 に答える 2

3

ツリーの深いレベルにある子を取得し、nそれらを反復処理する場合は、次のように実行できます。

def childrenAtLevel(tree, n):
    if n == 1:
        for child in tree.getchildren():
            yield child
    else:
        for child in tree.getchildren():
            for e in childrenAtLevel(child, n-1):
                yield e

次に、要素を4レベル深くするには、次のように言います。

for e in childrenAtLevel(root, 4):
     # do something with e

または、すべてのリーフノード(つまり、それ自体に子がないノード)を取得する場合は、次のように実行できます。

def getLeafNodes(tree):
    if len(tree) == 0:
         yield tree
    else:
         for child in tree.getchildren():
            for leaf in getLeafNodes(child):
                yield leaf
于 2013-02-08T20:25:23.723 に答える
2

itertools.chain.from_iterableネストの 1 レベルを平坦化します。nfunctools.reduce回適用するために使用できます(「n」回のオブジェクトメンバー呼び出しの圧縮):

from itertools import chain
from functools import reduce

for child in reduce(lambda x, _: chain.from_iterable(x), range(3), root):
    print(child.attrib)

getchildren推奨されないことに注意してください。ノードを反復すると、その子が直接生成されます。

于 2013-02-08T20:40:01.947 に答える