简体   繁体   English

根据递归python函数的返回值创建平面列表

[英]Creating a flat list from return values of a recursive python function

I am trying to compare two directories using the dircmp function in python 我正在尝试使用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))

I am trying to get a result like: 我试图得到这样的结果:

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

What is the best way to do this? 做这个的最好方式是什么?

Never used dircmp before...but I think this should work looking at your code... 以前从未使用过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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM