2

MS Word has this default non-logic way of numbering sections with I believe has manifested it self many other places. What I talk about is

...

1.8.1 Ninja

1.8.2 Gaab

1.9.1 Foo

1.10.1 Baa

...

But working with strings and wishing to sort would give the following order:

[1.10.1 Baa, 1.8.1 Ninja, 1.8.2 Gaab, 1.9.1 Foo]

Is there any easy and beautiful python way of solving this issue?

Community
  • 1
  • 1
Norfeldt
  • 8,272
  • 23
  • 96
  • 152
  • What you need is called a "natural sort", and there are many recipes and snippets implementing it. See, for example, [this SO question and its answers.](http://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort) – user4815162342 Dec 19 '14 at 14:39

3 Answers3

2

You need lambda with three keys obtained from section numbering i.e., three integers obtained from splitting section numbering as:

>>> lst = ['1.10.1 Baa', '1.8.1 Ninja', '1.8.2 Gaab', '1.9.1 Foo']
>>> sorted(lst, key=lambda x:([int(x) for x in x.split()[0].split('.')]))
['1.8.1 Ninja', '1.8.2 Gaab', '1.9.1 Foo', '1.10.1 Baa']
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36
1
sorted(section_names, key=lambda x: tuple(map(int, x.partition(" ")[0].split("."))))
filmor
  • 30,840
  • 6
  • 50
  • 48
0

Exploiting the fact that tuples are sorted in the order you want:

strList = ["1.8.1 Ninja",                                                        
  "1.8.2 Gaab",
  "1.9.1 Foo",
  "1.10.1 Baa"]

sorted(( (tuple(map(int, x.split('.'))), y)   # Sort according to list numbers
          for s in strList 
          for [x, y] in [s.split(' ', 1)]     # [x, y] = s.split(' ', 1)
                                              # Splits list in exactly 2 elems
      ))

# Out[43]:
# [((1, 8, 1), 'Ninja'),
# ((1, 8, 2), 'Gaab'),
# ((1, 9, 1), 'Foo'),
# ((1, 10, 1), 'Baa')]
musically_ut
  • 34,028
  • 8
  • 94
  • 106
  • Have a look at the answers from Bhat and me, you can exploit this fact without changing the elements of the `list` by using the `key` parameter of `sorted`. – filmor Dec 19 '14 at 16:04