Skip to main content
 首页 » 编程设计

python之有没有办法避免这种重复的代码

2025年05月04日22qq号

我写了一段非常简单的代码,但一直有这种唠叨的感觉,有一种更简单的方法来编写它。特别是其他两个;我觉得一定有办法避免在这个循环中写两个相同的 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 

请您参考如下方法:

在这里你根本不需要外层的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") 

当遍历空序列时,立即执行 for 语句的 else: 组。这与您的 if ...: ... else: ... 使用代码重复测试的效果完全相同。

如果 childreninfo['children']['page']['results'] 可以是无法迭代的不同假值(例如 None),在for 循环可迭代表达式中添加或()以强制对空序列进行迭代:

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