0

I want to sort a List with Strings by name:

I want the following:

a = ["Datei", "Datei-1", "Datei-2", "Datei-3", "Datei-4", "Datei-5", "Datei-6", "Datei-7", "Datei-8", "Datei-9", "Datei-10", "Datei-11", "Datei-12", "Datei-13", "Datei-14", "Datei-15", "Datei-16"]

I have got the following:

a = ["Datei", "Datei-1", "Datei-10", "Datei-11", "Datei-12", "Datei-13", "Datei-14", "Datei-15", "Datei-16" , "and so on"]

I have tried:

sorted(a)
flomax
  • 1
  • 1
  • 1

2 Answers2

1
In [1896]: a = ["Datei", "Datei-1","Datei-2", "Datei-10", "Datei-11", "Datei-12", "Datei-13", "Datei-14", "Datei-15", "Datei-16" , ]

In [1897]: sorted(a, key=lambda v:int(v.split('-')[-1]) if '-' in v else 0)
Out[1897]: 
['Datei',
 'Datei-1',
 'Datei-2',
 'Datei-10',
 'Datei-11',
 'Datei-12',
 'Datei-13',
 'Datei-14',
 'Datei-15',
 'Datei-16']
fixxxer
  • 15,568
  • 15
  • 58
  • 76
0

We can sort by splitting the string, and sorting by the numeric value. However your first element is missing a value, so we could put that first, as element 0:

def sort_func(entry):
    try:
        return int(x.split('-')[1])
    except IndexError:
        return 0

new_a = sorted(a, key=sort_func)

returns

['Datei', 'Datei-1', 'Datei-2', ..., 'Datei-9', 'Datei-10', 'Datei-11', ...]

supermitch
  • 2,062
  • 4
  • 22
  • 28
  • I don't think that's what Flomax is requesting. Besides, won't your suggestion fail for the first element of the list, which has no numeric portion? – Rob Kennedy May 01 '15 at 21:02
  • If that's not what he's requesting... then I dunno. I made a proper sort_function in an edit, for the first item, thanks. – supermitch May 01 '15 at 21:05