0

I am having few files like..

l.1,l.3,l.2,l.12,l.36,l.24

When i am sorting the list it is giving me...

l.1,l.12,l.2,l.24,l.3,l.36

How can i get them in this way?..

l.2,l.2,l.3,l.12,l.24,l.36

Note: because it is not permitting to add the actual file name as it is i ve given it as a list. but the actual file names are joined by '.' like l.1 l.2

I can write a bubble sort algorithm for that. But I want a simpler way..
Thanks

Sravan K Ghantasala
  • 1,058
  • 8
  • 14

3 Answers3

1

Here you go:

  l =  ['l.1','l.3','l.2','l.12','l.36','l.24']
  sorted(l, key = lambda x: int(x[2:]))
kofemann
  • 4,217
  • 1
  • 34
  • 39
1

In one line:

>>> li = ["l.1", "l.3", "l.2", "l.12", "l.36", "l.24"]
>>> sorted(li, key=lambda x: int(x.split(".")[-1]))
['l.1', 'l.2', 'l.3', 'l.12', 'l.24', 'l.36']
Johannes Charra
  • 29,455
  • 6
  • 42
  • 51
0

As stated in the Python documentation the sort function on a list takes multiple argument (relevant section here).

You can use the key argument to specific a function which gets the key. An implementation for you case could be:

def key_fn(n):
    return int(n.split('.')[-1])

You could then do:

l = ["l.1","l.3","l.2","l.12","l.36","l.24"]
l.sort(key=key_fn)
Johannes Charra
  • 29,455
  • 6
  • 42
  • 51
Exelian
  • 5,749
  • 1
  • 30
  • 49