How to sort a list of section numbers in Python?

Book sections are usually numbered as xxx , for example 1.2.3 . How to sort the list of section numbers?

Save section numbers as a list of strings.

 # a list of strings, section numbers ls = ['1.1', '1.10', '1.2', '1.2.3', '1.2.1', '1.9'] lists = sorted([s.split('.') for s in ls], key=lambda x:map(int, x)) # [['1', '1'], ['1', '2'], ['1', '2', '1'], ['1', '2', '3'], ['1', '9'], ['1', '10']] r = ['.'.join(sublist) for sublist in lists] #['1.1', '1.2', '1.2.1', '1.2.3', '1.9', '1.10'] 

However, my expected result:

 ['1.1', '1.10', '1.2', '1.2.1', '1.2.3', '1.9'] 
+3
python sorting list
source share
3 answers

Use a special comparison function that converts strings to sub-lists of integers. They will be correctly sorted without problems.

 In [4]: ls = ['1.1', '1.10', '1.2', '1.2.3', '1.2.1', '1.9'] In [5]: def section(s): ...: return [int(_) for _ in s.split(".")] ...: In [6]: sorted(ls, key=section) Out[6]: ['1.1', '1.2', '1.2.1', '1.2.3', '1.9', '1.10'] 
+7
source share

Like your comments, float is not the data type you need. In your case, you have an actual hierarchy of chapters / sections.

One simple (and remember, simple is better than complex) way is to represent the partition numbers as tuples. Since tuples are sorted lexicographically, they are naturally sorted in the right order:

 >>> lf = [(1, ), (1, 1), (1, 10), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (2, ), (1, 9)] >>> sorted(lf) [(1, ), (1, 1), (1, 3), (1, 4), (1, 5), (1, 6), (1, 7), (1, 8), (1, 9), (1, 10), (2, )] 

As we can see, this also works for tuples with different lengths.

If you want to save partitions as strings, natsort also does fine with dotted values:

 >>> s = ['1', '1.1', '1.10', '1.2'] >>> natsort.natsorted(s) ['1', '1.1', '1.2', '1.10'] 

You can also define your own SectionNumber class, but this is probably overkill.

+4
source share

Book sections are usually numbered as xxx

Why not save the partition numbers as tuples?

 sections = [(2, 4, 1), (1, 10, 3),(1, 2, 1), (1, 1, 10), (1, 2, 3), (1, 4, 6)] print(sorted(sections)) 

gives [(1, 1, 10), (1, 2, 1), (1, 2, 3), (1, 4, 6), (1, 10, 3), (2, 4, 1)]

+3
source share

All Articles