coolair
V2EX  ›  问与答

Python 如何将文件路径列表进行归类?

  •  
  •   coolair · Aug 27, 2020 · 1069 views
    This topic created in 2094 days ago, the information mentioned may be changed or developed.
    list_a = ['/usr/bin/a.sh', '/usr/bin/b.sh', '/usr/c.sh', '/usr/d.sh', '/bin/a.sh', '/bin/b.sh', '/bin/test/a.sh', '/bin/test/c.sh']
    
    ===>
    
    result = [['/usr/bin/a.sh', '/usr/bin/b.sh'], [ '/usr/c.sh', '/usr/d.sh'], ['/bin/a.sh', '/bin/b.sh'], ['/bin/test/a.sh', '/bin/test/c.sh']]
    

    也就是把目录相同的文件路径归到一个子列表中,如何操作更高效啊,谢谢。

    5 replies    2020-08-27 16:33:17 +08:00
    imn1
        1
    imn1  
       Aug 27, 2020
    先订层级
    /相同 15 层 /a
    /相同 15 层 /b/a
    这两个算一类还是两类?
    BBrother
        2
    BBrother  
       Aug 27, 2020
    根据"/"切分,切出来的每一部分都是一个节点,以类似 trie 的思路建树,所有非叶子节点就是你要的子目录
    ungrown
        3
    ungrown  
       Aug 27, 2020
    路径所有 part 全部割开,然后迭代放入多层级的字典
    coolair
        4
    coolair  
    OP
       Aug 27, 2020
    @imn1 #1 两类
    imn1
        5
    imn1  
       Aug 27, 2020
    如果只计算 basename 和 dirname 就简单
    dirs = {dirname(x) for x in list_a}
    result = [[x for x in list_a if x.startswith(y+'/')] for y in dirs]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4214 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 52ms · UTC 10:10 · PVG 18:10 · LAX 03:10 · JFK 06:10
    ♥ Do have faith in what you're doing.