3

I am trying to sort tuples in list that have field of mixed nature: LABEL.NUMBER. For example:

 aaaa.143
 aadf.23
 aaaa.8
 ..

So, I would like to sort first by LABEL as strings, and at the same by NUMBER as numbers, i.e. after sorting the should come:

 aaaa.8
 aaaa.143
 aadf.23
 ..

I have now the following:

for i in sorted(v_distribution.items(), key=lambda x: x[0]): 

which sorts using the whole filed as a string, so I get:

 aaaa.143
 aaaa.8
 aadf.23
 ..

How should I modify my lambda function to do the task?

pmod
  • 10,450
  • 1
  • 37
  • 50
  • 3
    Have you seen: http://stackoverflow.com/questions/11150239/python-natural-sorting – Jon Clements Sep 11 '13 at 11:29
  • @JonClements No, thank you for the link, I need to check the solution, maybe my question is to be duplicated... – pmod Sep 11 '13 at 11:33
  • @JonClements It turned out that solution posted here solves my specific task instead of general solution from your link. So I think it's not fully duplicate but a special case regarding the similar issue. – pmod Sep 11 '13 at 12:05

2 Answers2

2

Something like:

>>> s = ['aaaa.143', 'aadf.23', 'aaaa.8']
>>> def key_f(x):
...     head, tail = x.split('.', 1)
...     return (head, int(tail))
...
>>> sorted(s, key=key_f)
['aaaa.8', 'aaaa.143', 'aadf.23']

Although this can be done with lambda, it is better to separate key calculation into separate function.

Roman Bodnarchuk
  • 29,461
  • 12
  • 59
  • 75
  • Thank you, since it was tagged with lambda and tuples was in question, I will accept another answer, +1 anyway – pmod Sep 11 '13 at 11:58
1

You can do this with lambda as:

for i in sorted(v_distribution.items(), key=lambda x: (x.split('.', 1)[0], int(x.split('.', 1)[1]):
Paul Evans
  • 27,315
  • 3
  • 37
  • 54