2015-04-19 81 views
5

Plik wejściowy zawiera listę ścieżek plików. sugerują algorytm zrobić hierarchii wyjście sortowania jak poniżejSortowanie hierarchiczne ścieżek plików w pythonie

Wejście

A/file1 
A/B/C/D/file3 
A/B/file1 
A/B/file2 
A/B/C/D/file1 
A/file2 
A/W/X/Y/Z/file1 
A/W/file1 
A/W/X/file1 
A/file3 
A/B/C/file1 
A/W/X/Y/file1 
A/B/file2 

oczekiwany wynik

A/file1 
A/file2 
A/file3 

A/B/file1 
A/B/file2 

A/B/C/file1 

A/B/C/D/file1 
A/B/C/D/file3 


A/W/file1 

A/W/X/file1 

A/W/X/Y/file1 

A/W/X/Y/Z/file1 

próbował kodowania jak poniżej, wynik nie idzie zgodnie z oczekiwaniami

import sys,os 
d1,d2 = '','' 
l1 = [ x for x in open(sys.argv[1])] 
s2 = sorted(l1,key = lambda x : len(x.split('/'))) 
for linE in s2: 
    f1 = linE.strip('\n') 
    d1 = os.path.dirname(f1) 
    if d1 != d2 : print 
    d2 = d1 
    print linE, 

Wyjście prądowe

A/file1 
A/file2 
A/file3 

A/B/file1 
A/B/file2 

A/W/file1 

A/B/file2 

A/W/X/file1 

A/B/C/file1 

A/B/C/D/file3 
A/B/C/D/file1 

A/W/X/Y/file1 

A/W/X/Y/Z/file1 

proszę mi pomóc z algorytmem do tego samego

+0

można lepiej wyjaśnić rodzaj próbujesz zastosować? Twoje oczekiwane wyniki nie pokazują jasnej reguły. – jwilner

Odpowiedz

5
str = """A/file1 
A/B/C/D/file3 
A/B/file1 
A/B/file2 
A/B/C/D/file1 
A/file2 
A/W/X/Y/Z/file1 
A/W/file1 
A/W/X/file1 
A/file3 
A/B/C/file1 
A/W/X/Y/file1 
A/B/file2""" 

import string 
files = string.split(str, "\n") 

import os.path 
std = sorted(files, key=lambda file: (os.path.dirname(file), os.path.basename(file))) 

print std[0] 
for i in range(1,len(std)): 
    if os.path.dirname(std[i]) != os.path.dirname(std[i-1]): 
     print "" 
    print std[i] 
+0

Dzięki Amit .. Świetne myślenie .. to działa !! :) – user1228191