2016-09-29 2 views
2

Ich habe eine Liste von Dateinamen in der Form:Numerisch bestellt eine Liste basierend auf einem Muster

['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] 

Ich frage mich, wie diese Liste zu sortieren numerisch die Ausgabe zu erhalten:

['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt', 'comm_1_10.txt', 'comm_1_11.txt'] 

Antwort

3

Sie Split benötigt Zahlen sollten und wandeln sie in int

ss = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] 

def numeric(i): 
    return tuple(map(int, i.replace('.txt', '').split('_')[1:])) 

sorted(ss, key=numeric) 
# ['comm_1_1.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt', 'comm_1_10.txt', 'comm_1_11.txt'] 
1

ich wirklich glaube nicht, dass es ist eine beste Antwort, aber man kann Versuch es.

l = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] 

d = {} 

for i in l: 
    filen = i.split('.') 
    key = filen[0].split('_') 
    d[int(key[2])] = i 

for key in sorted(d): 
     print(d[key]) 
2

Eine Technik für diese Art von „human Sortierung“ verwendet wird, ist Schlüssel zu Tupeln spalten und numerischen Teile tatsächlichen Zahlen konvertieren:

ss = ['comm_1_1.txt', 'comm_1_10.txt', 'comm_1_11.txt', 'comm_1_4.txt', 'comm_1_5.txt', 'comm_1_6.txt'] 

print(sorted(ss, key=lambda x : map((lambda v: int(v) if "0" <= v[0] <= "9" else v), re.findall("[0-9]+|[^0-9]+", x)))) 

oder, besser lesbar

def sortval(x): 
    if "0" <= x <= "9": 
     return int(x) 
    else: 
     return x 

def human_sort_key(x): 
    return map(sortval, re.findall("[0-9]+|[^0-9]+", x)) 

print sorted(ss, key=human_sort_key) 

Die Idee besteht darin, zwischen numerischen und nicht-numerischen Teilen zu teilen und die Teile in eine Liste zu setzen, nachdem die numerischen Teile in tatsächliche Zahlen umgewandelt wurden (so dass 10 nachkommt).

Lexikografische Sortierung der Listen ergibt das erwartete Ergebnis.

Verwandte Themen