1
votes

In text widget, indexes are used to point to positions within the text handled by the text widget. Positions withing the text in the text widget are marked using string indexes of the form “line.column”. Line numbers start at 1, while column numbers start at 0.

The problem is how do you sort a list of indexes? For instance:

unsorted_indexes = ['1.30', '1.0', '1.25',  '3.10', '3.100', '3.1', '3.8']
# expected result: ['1.0', '1.25', '1.30',  '3.1', '3.8', '3.10', '3.100']

# cant sort as strings:
print(sorted(unsorted_indexes))
# gives incorrect values: ['1.0', '1.25', '1.30', '3.1', '3.10', '3.100', '3.8']

# cant convert to float
print(sorted([float(index) for index in unsorted_indexes]))
# [1.0, 1.25, 1.3, 3.1, 3.1, 3.1, 3.8]

If you transform string index into some other form, than off course you need a way back to the original form. In the above example doing float('3.1') and float('3.100') results in float values of 3.1. Cant return to '3.1' or '3.100'. Or maybe in tkinter there is some mechanism already for this, and I'm missing it?

1

1 Answers

2
votes

Hopes this can help you: Here the code:

>>> unsorted_indexes = ['1.30', '1.0', '1.25',  '3.10', '3.100', '3.1', '3.8']
>>> unsorted_indexes.sort(key=lambda x: [x.split('.')[0], int(x.split('.')[1])])
>>> unsorted_indexes
['1.0', '1.25', '1.30', '3.1', '3.8', '3.10', '3.100']
>>>