2

我有一个lxml.objectify从 RESTful 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

总的来说,结构还不错(假设您需要在设置中调用modify1+项目——如果“只有一个”,即如果is_what_I_want最多为一个设置设置标志,那当然是不同的,因为您可以并且应该使用循环中的 a break——for但这不是我从您的 Q 中得到的您意图的印象,请澄清我是否有误!)。有一个冗余:

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 回答