有办法避免这种重复的代码吗?

时间:2018-11-01 14:04:31

标签: python python-3.x

我写了一段很简单的代码,但是一直有这种烦恼的感觉,这是一种更简单的编写方法。特别是另外两个;我觉得必须有一种方法可以避免在此循环中编写两个相同的else子句。我要密吗?

parentid = ca.get_parent_id(spacename, parentname)
if parentid is None:
    raise Exception("Unable to find parent page")

for subpage in subpages:
    ## check to see if subpage is a child of the previous page
    childreninfo = ca.get_page_children(parentid)
    if childreninfo['children']['page']['results']:
        for pageinfo in childreninfo['children']['page']['results']:
            if pageinfo['title'] == subpage:
                break
        else:
            # if we find the page somewhere in the space but it's not a child, stop! 
            info = ca.get_page_info_by_title(subpage, spacename)
            if len(info['results']) == 1:
                raise Exception("Found page but not in right location")
    else:
        # if we find the page somewhere in the space but it's not a child, stop!
        info = ca.get_page_info_by_title(subpage, spacename)
        if len(info['results']) == 1:
            raise Exception("Found page but not in right location")

    ## DO STUFF with subpage here

1 个答案:

答案 0 :(得分:5)

这里根本不需要外部if:..else:。只需直接进入for循环:

for subpage in subpages:
    ## check to see if subpage is a child of the previous page
    childreninfo = ca.get_page_children(parentid)
    for pageinfo in childreninfo['children']['page']['results']:
        if pageinfo['title'] == subpage:
            break
    else:
        # if we find the page somewhere in the space but it's not a child, stop! 
            info = ca.get_page_info_by_title(subpage, spacename)
            if len(info['results']) == 1:
                raise Exception("Found page but not in right location")

循环空序列时,将立即执行else:语句的for套件。这与进行代码复制的if ...: ... else: ...测试完全一样。

如果childreninfo['children']['page']['results']可能是另一个不能重复的假值(例如None),请在or ()循环中添加for可迭代的表达式,以强制在空序列上进行迭代:

for pageinfo in childreninfo['children']['page']['results'] or ():