简化if - if阶梯 - python

时间:2018-03-22 05:51:07

标签: python python-2.7 if-statement

如果需要,我需要将这些代码行简化为少于4行。不知道我怎么能做到这一点:

    for response in response_json:
        for appliance in response['versanms.ApplianceStatusResult']['appliances']:
            temp_item = OrderedDict()
            if 'name' in appliance:
                temp_item['name'] = appliance['name']
            if 'type' in appliance:
                temp_item['type'] = appliance['type']
            if 'ping-status' in appliance:
                temp_item['ping-status'] = appliance['ping-status']
            if 'sync-status' in appliance:
                temp_item['sync-status'] = appliance['sync-status']
            if 'services-status' in appliance:
                temp_item['services-status'] = appliance['services-status']
            if 'orgs' in appliance:
                temp_item['orgs'] = appliance['orgs']
            if 'ownerOrg' in appliance:
                temp_item['ownerOrg'] = appliance['ownerOrg']
            if 'softwareVersion' in appliance:
                temp_item['softwareVersion'] = appliance['softwareVersion']
            if 'ipAddress' in appliance:
                temp_item['ipAddress'] = appliance['ipAddress']
            if appliance is not None:
                appliance_list.insert(0, temp_item)
return {'appliance': appliance_list}

需要删除if,因为我们的代码验证工具在一种方法中不会超过4 :(

谢谢

2 个答案:

答案 0 :(得分:6)

替换所有这些:

if 'name' in appliance:
    temp_item['name'] = appliance['name']
if 'type' in appliance:
    temp_item['type'] = appliance['type']
if 'ping-status' in appliance:
    temp_item['ping-status'] = appliance['ping-status']
if 'sync-status' in appliance:
    temp_item['sync-status'] = appliance['sync-status']
if 'services-status' in appliance:
    temp_item['services-status'] = appliance['services-status']
if 'orgs' in appliance:
    temp_item['orgs'] = appliance['orgs']
if 'ownerOrg' in appliance:
    temp_item['ownerOrg'] = appliance['ownerOrg']
if 'softwareVersion' in appliance:
    temp_item['softwareVersion'] = appliance['softwareVersion']
if 'ipAddress' in appliance:
    temp_item['ipAddress'] = appliance['ipAddress']

带循环:

for x in ['name', 'type', 'ping-status', 'sync-status',
          'services-status', 'orgs', 'ownerOrg',
          'softwareVersion', 'ipAddress']:
    if x in appliance:
        temp_item[x] = appliance[x]

答案 1 :(得分:0)

如果您想使用设备中的所有值而不是少数几个值,那么在appliance.keys()中的for ..将起作用。

appliance = { 'name':'this is the name', 'type': 'this is the type', 'ping-status': 'this is the ping status' }
temp_item = OrderedDict()

for field_name in appliance.keys():
    temp_item[field_name] = appliance[field_name]

print temp_item

输出 {'ping-status':'这是ping状态','type':'这是类型','名称':'这是名字'}