I must implement sorting the list of strings in a way which is much similar to sorted
function, but with one important distinction. As you know, the sorted
function accounts space character prior digits character, so sorted(['1 ', ' 9'])
will give us [' 9', '1 ']
. I need sorted
that accounts digit character prior space chars, so in our example the result will be ['1 ', ' 9']
.
Update
As I understand, by default the sorted
behaviour relies on the order of chars in ascii 'alphabet' (i.e. ''.join([chr(i) for i in range(59, 127)])
), so I decided to implement my own ascii 'alphabet' in the my_ord
function.
I planned to use this function in junction with simple my_sort
function as a key for sorted
,
def my_ord(c):
punctuation1 = ''.join([chr(i) for i in range(32, 48)])
other_stuff = ''.join([chr(i) for i in range(59, 127)])
my_alphabet = string.digits + punctuation1 + other_stuff
return my_alphabet.find(c)
def my_sort(w):
return sorted(w, key=my_ord)
like this: sorted([' 1 ', 'abc', ' zz zz', '9 '], key=my_sort)
.
What I'm expecting in this case, is ['9 ', ' 1 ', ' zz zz', 'abc']
. Unfortunately, the result not only doesn't match the expected - moreover, it differs from time to time.