2

lxml.objectifyRESTful Web サービスから取得したデータ構造があります。存在する場合は設定を変更し、存在しない場合は作成する必要があります。現在、次のようなものがありますが、見苦しいと感じています。私が探している構造には、すべて同じ構造を持つサブ要素のリストがあるため、残念ながら特定のタグを探すことはできません。

thing_structure = lxml.objectify(get_from_REST_service())
found_thing = False
if thing_structure.find('settings') is not None:
    for i, foo in enumerate(thing_structure.settings):
        if foo.is_what_I_want:
            modify(thing_structure.settings[i])
            found_thing = True
if not found_thing:
    new = lxml.etree.SubElement(thing_structure, 'setting')
    modify(new)

send_to_REST_service(thing_structure)
4

2 に答える 2

2

全体として、構造はそれほど悪くありません (設定で 1 つ以上の項目を呼び出す必要があると仮定するとmodify 1 つだけ」の場合、つまり、is_what_I_wantフラグが最大で 1 つの設定に対して設定される場合、それはもちろん異なります)。 、ループbreakからa を使用することができ、また使用する必要がありforます-しかし、それは私があなたの Q から得るあなたの意図の印象ではありません。私が間違っていた場合は明確にしてください!)。冗長性が 1 つあります。

for i, foo in enumerate(thing_structure.settings):
    if foo.is_what_I_want:
        modify(thing_structure.settings[i])
        found_thing = True

それをi使用して再び同じものを取得することfooは、ここでは役に立たないため、次のように単純化できます。

for foo in thing_structure.settings:
    if foo.is_what_I_want:
        modify(foo)
        found_thing = True

アイテムを再バインドする場合、つまり などの割り当てを実行する場合にのみ、インデックスが必要になりますthing_structure.settings = whatever。(ところで、以外の名前はfoo問題ありません;-)。

于 2010-09-29T17:47:11.703 に答える
0

私はこれを書きます:

thing_structure = lxml.objectify(get_from_REST_service())
if thing_structure.find('settings') is not None:
    foos = [foo for foo in thing_structure.settings if foo.is_what_I_want]
        or [lxml.etree.SubElement(thing_structure, 'setting')]
    for foo in foos:
       modify(foo)
send_to_REST_service(thing_structure)

私はそれを気にせずis not None、できる限り排除します。ここで可能であれば、次のように書きます。

if thing_structure.find('settings'):
于 2010-10-21T04:04:41.663 に答える