从递归python函数的返回值创建一个平面列表

时间:2012-08-16 23:13:30

标签: python recursion

我正在尝试使用python

中的dircmp函数比较两个目录
def cmpdirs(dir_cmp):
    for sub_dcmp in dir_cmp.subdirs.values():
        cmpdirs(sub_dcmp)
    return dir_cmp.left_only, dir_cmp.right_only, dir_cmp.common_files

if __name__ == '__main__':
    dcmp = dircmp('dir1', 'dir2')
    result = list(cmpdirs(dcmp))

我想得到一个结果:

([file1,file2],[file3,file4],[file5,file6])

这样做的最佳方式是什么?

1 个答案:

答案 0 :(得分:1)

之前从未使用过dircmp ......但我认为这应该可以查看你的代码...

def cmpdirs(dir_cmp):
    # make copies of the comparison results
    left   = dir_cmp.left_only[:]
    right  = dir_cmp.righ_only[:]
    common = dir_cmp.common_files[:]

    for sub_dcmp in dir_cmp.subdirs.values():
        sub_left, sub_right, sub_common = cmpdirs(sub_dcmp)

        # join the childrens results
        left   += sub_left
        right  += sub_right
        common += sub_common

    # return the merged results
    return (left, right, common)

if __name__ == '__main__':
    dcmp   = dircmp('dir1', 'dir2')
    result = cmpdirs(dcmp)